C gotchas: fgetc and EOF
The current ISO C standard, informally named "C11", as well as the previous version of the standard, "C99", does not bar an implementation from letting sizeof(int)
be 1. This causes trouble for some I/O functions, such as getchar()
, because the value returned is a value of type unsigned char
cast to int
. If sizeof(int)
is 1, then that means any value returned by such a function is a potentially legitimate value. Before the end of the file is reached and before any error occurs, EOF
in particular may be returned. As a result, you can't always rely on a return value of EOF
being an indicator to stop reading from a file.
This means you're forced to call feof()
to further verify whether you need to stop reading input or not. Personally, I find this similar to the unwieldy strtoXX()
functions, where a legitimate value may be returned, forcing you to check errno
. The only difference is that two checks are required instead of one.
This affects a relatively small number of implementations where EOF
matches the character read. After all, a digital sound processor must be very fast when reading information, so 8-bit I/O as used on a desktop computer is not necessarily a great idea (especially if you can't access anything smaller than 32 bits without bit masks).
More info can be found in the linked discussion on Stack Overflow.http://pastebin.com/5MdWNfpN
contains an example wrapper function for fgetc()
that handles this corner case.