Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text-file until EOF using fgets in C

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?

like image 942
Johan Avatar asked Aug 16 '16 13:08

Johan


2 Answers

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.

like image 192
bigahega Avatar answered Sep 22 '22 05:09

bigahega


What you have done is 100% OK, but you can also simply rely on the return of fgets as the test itself, e.g.

char line[100 + 1] = "";  /* initialize all to 0 ('\0') */

while (fgets(line, sizeof(line), tsin)) { /* tsin is FILE* input */
    /* ... doing stuff with line */
}

Why? fgets will return a pointer to line on success, or NULL on failure (for whatever reason). A valid pointer will test true and, of course, NULL will test false.

(note: you must insure that line is a character array declared in scope to use sizeof line as the length. If line is simply a pointer to an array, then you are only reading sizeof (char *) characters)

like image 27
David C. Rankin Avatar answered Sep 26 '22 05:09

David C. Rankin