0

I created 2 function. One for login and another for signup. It's working fine for only one user but for multiple user it's not working. It's only read the first two string from the file. How can I fix it and make it to read second or more set of data from file? Here is my code:

//login (reading data)
login() {
    system("cls");
    system("color 3");
    char username[10], password[10], un[10], pwd[10];
    FILE *fp;
    fp = fopen("stored_data.txt","r");
    fscanf(fp, "%s%s", username, password);
    printf("Enter your username: ");
    fflush(stdin);
    gets(un);
    printf("Enter your password: ");
    fflush(stdin);
    gets(pwd);
    if ((strcmp(username,un)==0)&&(strcmp(password,pwd)==0)) {
        printf("Login successful, welcome %s.\n",un);
    }
    else {
        system("cls");
        system("color 4");
        printf("Invalid username or password.");
    }
    fclose(fp);
}
//Sign up (store data)
signup() {
    system("cls");
    system("color 3");
    char username[10], un[10], pwd[10];
    FILE *fp;
    fp = fopen("stored_data.txt","r");
    fscanf(fp, "%s", username);
    fp = fopen("stored_data.txt","a");
    printf("Enter your username: ");
    fflush(stdin);
    gets(un);
    if((strcmp(username,un)==0)) {
        printf("User already existed.\n");
    }
    else {
        printf("Enter your password: ");
        fflush(stdin);
        gets(pwd);
        fprintf(fp,"%s %s",un,pwd);
        printf("New user's information added successfully.\n");
    }
    fclose(fp);
}
Garuda
  • 3
  • 3

1 Answers1

0

You should look for the name after the user entered his name and password. By this line

fscanf(fp, "%s%s", username, password);

You are reading the first username and password in your file. Instead, you should move this into a while loop.

...
printf("Enter your username: ");
fflush(stdin);
gets(un);
printf("Enter your password: ");
fflush(stdin);
gets(pwd);
while(!feof(fp)){
    fscanf(fp, "%s%s", username, password);
    if (strcmp(username,un) == 0){
        if(strcmp(password, pwd) == 0)
            printf("Login successful, welcome %s.\n",un);
        else break;
    }
}
...
pc18
  • 16
  • 1