Search code examples
cfgets

fgets trouble shooting


#include <stdio.h>
#include <string.h>
int main()
{
    FILE *pInFile;
    pInFile = fopen("fileName.txt", "r");
    char line[200];

    while (fgets(line, sizeof(line), pInFile)) { 
        printf("\n%s", line);
        if (strcmp(line, "C")==1)
            printf("Success");

    }

    return 0;
}

So goal of the program is print "Success" after each time it reads the line, which in this case is "C". For example, my text file looks like this

C
C
C
C

And I want it to print

C
Success
C
Success
C
Success
C
Success

However, it is for some reason only printing this

C
Success
C
Success
C
Success
C

And leaving out the last "Success". I have absolutely no clue why it is doing this.


Solution

  • strcmp() will return 0 if the two strings are equal.

    try changing the condition with strcmp() to this:

    if (line[0] == 'C') {
        printf("Success");
    }
    

    Explanation as to why you are getting the output you posted:

    1. fgets on the first line gets the following into line:

      C\n
      
    2. so when you strcmp(line, "C") == 1 it succeeds because strcmp() returns >0 if 2nd argument > 1st argument.

    3. this happens for all the lines except the last one.

    4. Therefore in the last line strcmp() returns 0 as the strings are equal and you don't print succeed

    To solve this do either what Gangadhar suggested in his post or what I showed above.