For my code I need to make a .txt file containing a username (first name) and a password (last name). My code needs to read that file. If I entered the correct user name and password it will log me in. If it is incorrect it not log me in. So far in my name.txt file (the file containing my usernames and passwords) I have Lebron James, Joe Smith. As I run my code i just get "could not open file names.txt" to display in the command prompt. Any idea on what changes i need to make to my code?
//This is my code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_USER 32
void get_input(const char *pszPrompt, char *cpszWord, const size_t iLength)
{
while (1) {
printf("%s> ", pszPrompt);
if (fgets(cpszWord, iLength * sizeof(char), stdin)) {
break;
}
}
size_t iLen = strlen(cpszWord);
if (cpszWord[iLen - 1] == '\n')
cpszWord[iLen - 1] = 0;
}
int compare(FILE *f, const char *szUser, const char *szPassword)
{
int iFound = 0;
char szName[MAX_USER], szPW[MAX_USER];
while (!feof(f) && iFound != 2) {
iFound = 0;
if (fscanf(f, "%s %s", szName, szPW) == 2) {
if (!strcmp(szName, szUser)) {
++iFound;
}
if (!strcmp(szPassword, szPW)) {
++iFound;
}
}
}
return iFound;
}
int main()
{
const char szFile[] = "names.txt";
char user[MAX_USER], password[MAX_USER];
int iFound = 0;
do {
FILE *f = fopen(szFile, "rt");
if (!f) {
printf("Could not open file %s\n", szFile);
break;
}
get_input(" User", user, sizeof(user));
get_input("Password", password, sizeof(password));
iFound = compare(f, user, password);
fclose(f);
if (iFound == 1) {
printf("Wrong Password!\n");
}
} while (iFound && iFound < 2);
if (iFound == 2) {
printf("Welcome User!\n");
}
system("pause");
return 0;
}
If you mean where to specify a known path to your existing file, then just before the filename, e. g.:
If you mean where to put your file without having to specify a path, then you can find out with e. g.: