This is a practice code for a login system.
struct login
{
char username[30];
char password[20];
};
void login (void);
void registration (void);
int main (void)
{
int option;
printf("Press '1' to Register\nPress '2' to Login\n\n");
scanf("%d",&option);
getchar();
if(option == 1)
{
registration();
}
else if(option == 2)
{
login();
}
}
void login (void)
{
char username[30],password[20];
FILE *log;
log = fopen("login.txt","r");
if (log == NULL)
{
fputs("Error at opening File!", stderr);
exit(1);
}
struct login l;
printf("\nPlease Enter your login credentials below\n\n");
printf("Username: ");
printf("\n");
fgets(username, 30, stdin);
printf("\nPassword: ");
printf("\n");
fgets(password, 20, stdin);
while(fread(&l,sizeof(l),1,log))
{
if(strcmp(username,l.username)==0 && strcmp(password,l.password)==0)
{
printf("\nSuccessful Login\n");
}
else
{
printf("\nIncorrect Login Details\nPlease enter the correct credentials\n");
}
}
fclose(log);
return;
}
void registration(void)
{
char firstname[15];
FILE *log;
log=fopen("login.txt","w");
if (log == NULL)
{
fputs("Error at opening File!", stderr);
exit(1);
}
struct login l;
printf("Welcome to UrBook. Please choose a username and password as credentials for system login.\nEnsure the username is no more than 30 characters long.\nEnsure your password is at least 8 characters long and contains lowercase, uppercase, numerical and special character values.\n");
printf("\nEnter Username:\n");
scanf("%s",l.username);
printf("\nEnter Password:\n");
scanf("%s",l.password);
fwrite(&l,sizeof(l),1,log);
fclose(log);
printf("\nRegistration Successful!\n");
printf("Press any key to continue...");
getchar();
login();
}
I can't seem to figure out the problem in the code. It always shows incorrect login details no matter what I put in. As an example, I wrote login as abc, password as 123. And similarly with some different inputs, but the same error was being shown. I also tried to use fscanf instead of fgetf, but it didn't work.