The char array compares and the while loop does not work properly in C


I have this function named CheckEmployee. It opens a text file and check if the id the user entered exists in the record:

void CheckEmployee()
    char empID[5];

    printf("Key in Employee ID: ");
    scanf("%s", &empID);

    FILE *fp = fopen("Employees.txt", "r");
    char lineOfText[40];

    while (fgets(lineOfText, 40, fp))
        char id[6];
        strncpy(id, lineOfText, 5);
        id[5] = 0;

        if (id == empID)

The texfile contains the following:

E0001de Guzman, Franz Miguel C.
E0002de Guzman, Fernan Ralph C.

with 40 characters each line including white spaces. The problem is:

  1. The while loops 4 times.(Should be twice only since there is only 2 records to traverse.)
  2. The program has a runtime error in if (id == empID). But when I replaced it with if (strcmp(id, empID) == 0), the answer is false.

UPDATE: strcmp is now working. thanks to @barak manos. The while looping 4 times still persists, but I get the result that I want.

To begin with, the char empID[5] and char id[6] look suspiciously short for your input.

Second, the value of expression id == empID is always false, since you are essentially comparing memory addresses of two statically allocated arrays.

The expression strcmp(id,empID) == 0 should yield the result you're looking for, assuming that the id and empID arrays are sufficiently large to store the text that you are reading into them.

Keep in mind that string routines such as strcmp, strcpy, strlen, printf expect null-terminated strings as input. So you have to make sure that each char array used for that purpose is large enough to store the input text plus an additional \0 character.