The problem of testing the error state arose due to a regional case in C.
fgetc() returns an int . Its values ββare in the range of unsigned char and EOF , (some negative number).
int ch; while ((ch = fgetc(fp)) != EOF) { // do something with ch } if (ferror(fp)) Handle_InputError(); if (feof(fp)) Handle_EndOffFile(); // Usually nothing special
However, C allows unsigned char have a wider range than a positive int number. Converting a unsigned char to int has a specific implementation behavior, which can lead to the conversion of the unsigned char value to a negative int - and the value corresponding to EOF .
Such platforms are rare, but not in the mainstream of 2015. Most of them will have UCHAR_MAX <= INT_MAX , and this style is commonly used. It is doubtful that these platforms will become commonplace due to the amount of code, as above, which relies on EOF other than unsigned char converted to int .
If the code should handle the rare case when UCHAR_MAX > INT_MAX , then
int c; for (;;) { c = fgetc(file); if (c == EOF) { if (feof(file)) break; if (ferror(file)) break; // fall through if both if fail. } // do stuff with c }
A popular link in while (! Feof (file)) is always incorrect? emphasizes that the error code is often made using the results of fgetc(in) before checking for problems. Both of the above codes check the error conditions before using the result of fgetc() .
The second code handles all situations, including those that can only be applied to a computer sitting in some long-forgotten garbage heap. The first is much more common.
chux
source share