The short answer is NO. Here is why:
If fgets
successfully read the '\n'
at the end of the line, the end-of-file indicator in the FILE
structure has not been set. Hence feof()
will return 0
, just like it should before reading anything, even on an empty file.
feof()
can only be used to distinguish between end-of-file and read-error conditions after an input operation failed. Similarly, ferr()
can be used to check for read-error after an input operation failed.
Programmers usually ignore the difference between end-of-file and read-error. Hence they only rely on checking if the input operation succeeded or failed. Thus they never use feof()
, and so should you.
The behavior is somewhat similar as that of errno
: errno
is set by some library functions in case of error or failure. It is not reset to 0
upon success. Checking errno
after a function call is only meaningful if the operation failed and if errno
was cleared to 0
before the function call.
If you want to check if you indeed reached to the of file, you need to try and read extra input. For example you can use this function:
int is_at_end_of_file(FILE *f) {
int c = getc(file);
if (c == EOF) {
return 1;
} else {
ungetc(c, file);
return 0;
}
}
But reading extra input might not be worthwhile if reading from the console: it will require for the user to type extra input that will be kept in the input stream. If reading from a pipe or a device, the side effect might be even more problematic. Alas, there is no portable way to test if a FILE
stream is associated with an actual file.