Reading text-file until EOF using fgets in C

Johan picture Johan · Aug 16, 2016 · Viewed 35.5k times · Source

what is the correct way to read a text file until EOF using fgets in C? Now I have this (simplified):

char line[100 + 1];
while (fgets(line, sizeof(line), tsin) != NULL) { // tsin is FILE* input
   ... //doing stuff with line
}

Specifically I'm wondering if there should be something else as the while-condition? Does the parsing from the text-file to "line" have to be carried out in the while-condition?

Answer

bigahega picture bigahega · Aug 16, 2016

According to the reference

On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).

So checking the returned value whether it is NULL is enough. Also the parsing goes into the while-body.