so I am trying to use struct and txt files to build a login form, I use a function for registration that saves username and password to txt file and another function for the login part by reading and comparing values from what the user input.
However the code seems to compare only the first line of username and password! The rest only gives wrong credentials, how do I make it compare the rest?
Struct
struct user
{
char userID[10];
char username[50];
char password[50];
};
Register Function
char registration()
{
system("cls");
printf ("--------------------------------------------------------------------------------------\n");
printf("\t\t\t\tWelcome to Registration Page\n");
printf ("--------------------------------------------------------------------------------------\n\n");
date();
struct user person;
printf("Enter the UserID: ");
scanf(" %s", person.userID);
printf("\nEnter the username: ");
scanf(" %s", person.username);
printf("\nEnter the password: ");
scanf(" %s", person.password);
printf("This person has username %s and password %s\n", person.username, person.password);
FILE *outfile;
// open file for writing
outfile = fopen ("user.txt", "a");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
// write struct to file
fwrite (&person, sizeof(struct user), 1, outfile);
fclose(outfile);
if(fwrite != 0)
printf("\ncontents to file written successfully !\n");
else
printf("error writing file !\n");
return 0;
}
Login function:
int login()
{
//system("cls");
printf ("--------------------------------------------------------------------------------------\n");
printf("\t\t\t\tWelcome to Login Page\n");
printf ("--------------------------------------------------------------------------------------\n\n");
date();
char username[50];
char password[50];
FILE *infile;
struct user person;
printf("\nPlease Enter your Username, Password to Proceed\n\n");
printf("\n\nUsername: ");
scanf(" %s", &username);
printf("\nPassword: ");
scanf(" %s", &password);
infile = fopen ("user.txt", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
// read file contents till end of file
while(fread(&person, sizeof(struct user), 1, infile)){
if(strcmp(username,person.username) == 0 && \
strcmp(password, person.password) ==0)
{
hrmenu();
break;
}
else
{
printf("Wrong Credentials, Please try again!\n");
login();
}
}
fclose(infile);
return 0;
}
infiletwice inlogin()? (BTW, useperrorfor error reporting, it knows why the file was not opened.)"%s"has no effect.