0

I have users.txt file and this file content like this

  • user1 1223
  • user3 7891
  • user3 5680

and now I want to read file content and compare with string which is passed as a function argument.

Note - example: userloging = "user1 1223"

int sign_in(char *userloging ) {

    char buffer[100];
    FILE *fp = fopen("user.txt", "r");                  
    while (fgets(buffer, sizeof(buffer), fp)) {
    
    // in here how can I compare and if found return 1; 
  }

  fclose(fp);

 }
ryyker
  • 22,849
  • 3
  • 43
  • 87
vepa
  • 1
  • 1

1 Answers1

0

You are looking at each entire line read from file (as you loop through 1 by 1) to see if within each line there exists a particular user login. Because each entire line may have content other than just the user login, two immediate options jump out:

  • remove all content from the file line other than content of interest. (eg \n, etc.) and use strcmp() to compare against the argument userloging
  • identify an exact match to userloging by searching for it as a sub-string of the line read from the file using strstr.

Either method will work. I prefer strstr() as it is adequate for the purpose and simpler to code. (no parsing required to clean up the string.) Following is an example using strstr():

Edited to use userloging input argument...

int sign_in(char *userloging ) 
{
    char buffer[100];
    int status = 0;//add this, see why below
    FILE *fp = fopen("user.txt", "r");                  
    if(fp)(//always test to make sure successful open occurred.
    {
        while (fgets(buffer, sizeof(buffer), fp)) {
        {
            if(strstr(buffer, userloging ))
            {
                // printf("Found %s\n", userloging );//optional
                //return 1; //if return here, cannot fclose(fp)
                status = 1;//user login has been found, leave loop and return
                break;
            }
        }
        fclose(fp);
    }
    return status;
}
ryyker
  • 22,849
  • 3
  • 43
  • 87
  • str_array[3][] give me erro is incomplete type is not allowedC/C++(70) – vepa Jan 12 '21 at 21:39
  • @Vepa - it should have been `char str_array[][20] =... ` Anyway, I edited it out to use your input argument `userloging`. Insert into your code and make adjustments to fit your needs – ryyker Jan 12 '21 at 21:39