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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With