If a file has been read to its end (that is, the current file position
is the end of the file), a flag indicating this, called the
end-of-file indicator, will be set to TRUE. You can check
whether the end-of-file indicator has been set (and therefore whether
the current file position is the end of the file), with the feof
function. This function takes a single argument (a stream), and returns
TRUE (a nonzero value) if the end of the file has been reached,
and FALSE (zero) otherwise.
Another flag, the error indicator, indicates whether an error has
occurred during an earlier operation on the stream. It returns
TRUE if there has been an error, and FALSE otherwise. You
can check the error indicator for a stream with the ferror
function. This function takes a single argument (a stream), and returns
TRUE (a nonzero value) if an error has occured during an
operation on the stream, and FALSE (zero) otherwise.
Unfortunately, ferror will not tell you what the error was, or
when it occurred, only whether there has been an error. To get a more
detailed diagnosis, you can check the global system variable errno.
(See Usual file name errors.)
It is possible to reset the error and end-of-file indicators once they
have been set for a stream. To do so, simply pass the stream to the
function clearerr; this will set both the error and end-of-file
indicators back to 0. The clearerr function does not return a
value.
You should not simply reset the error flag and try a stream operation
that failed a second time. Because of buffering, you may lose or repeat
data when writing, or access the wrong part of the file when reading.
Before you try a failed stream operation again, you should seek to a
known file position. (See File position.) However, most errors
cannot be recovered from anyway -- trying the operation again will
likely result in the same error -- so it is probably better to have
your program report the error to the user and exit than to write
complicated error-recovery routines for stream operation.
An example of these functions will not be useful until we have
introduced single-character I/O. See getc and fgetc, if you want to
read a code example that uses the feof and ferror
functions.