Certainly fgetc() returns EOF when end-of-file or an input error occurs.
Is that all and does that mean no more data is available?
FILE *inf = ...;
int ch;
while ((ch = fgetc(inf)) != EOF) {
;
}
if (feof(inf)) puts("End-of-file");
else if (ferror(inf)) puts("Error");
else puts("???");
Is testing with feof(), ferror() sufficient?
Note: EOF here is a macro that evaluates to some negative int, often -1. It is not a synonym for end-of-file.
I have found some questions and more that are close to this issue, yet none that enumerate all possibilities.
No, there are more ways for
EOF.An
EOFdoes not certainly mean no more data - it depends.The C library lists three cases where
fgetc()returnsEOF.Recall each stream, like
stdin, has an end-of-file indicator and error indicator.stream just encountered the end-of-file
(Most common) An attempt has been made to get more data, but there was none.
end-of-file indicator for the stream is set
The stream first examines its end-of-file indicator. If it sees that the indicator is set, it returns
EOF. No attempt is made to see if more data exists. Some types of streams will reportEOF, but data will have arrived after the priorEOFreport. Until the end-of-file indicator is cleared as withclearerr(), the return remainsEOF. Example 1. Example 2.Input error
The stream error indicator is not examined. Yet the function failed for some reason to read data other than end-of-file. A common example is
fputc(stdin). Often input errors are persistent. Some are not. More data may be available. The common strategy is to end the input.Output
When
ferror()is true, it does not mean the error just occurred, just sometime in the past.Other cases
Apparent
EOFdue to improperly saving ascharfgetc()returns anintwith a value in theunsigned charrange andEOF- a negative value.When
fgetc()reads character code 255, yet saves that as acharon a system wherecharis signed, that commonly results in thecharhaving the same value asEOF, yet end-of-file did not occur.Output
Systems where
UCHAR_MAX == UINT_MAX. Rare.(I have only come across this in some older graphics processors, still something C allows.) In that case,
fgetc()may read anunsigned charoutside theintrange and so convert it toEOFon the function return. Thusfgetc()is returning a character code that happens to equalEOF. This is mostly an oddity in the C history. A way to mostly handle is:Such pedantic code is rarely needed.
Undefined behavior
Of course when UB occurs, anything is possible.
A robust way to handle the return from
fgetc().If code needs to look for data after end-of-file or error, call
clearerr()and repeat theif()block.