Why does fgetc() return int instead of char?

ISO C mandates that fgetc() returns an int since it must be able to return every possible character in addition to an end-of-file indicator.

So code that places the return value into a char, and uses it to detect EOF, is generally plain wrong and should not be used.


Having said that, two of the examples you gave don’t actually do that.

One of them uses fseek and ftell to get the number of bytes in the file and then uses that to control the read/write loop. That’s could be problematic since the file can actually change in size after the size is retrieved but that’s a different problem to trying to force an int into a char.

The other uses feof immediately after the character is read to check if the end of file has been reached.


But you’re correct in that the easiest way to do it is to simply use the return value correctly, something like:

int charInt;
while ((charInt = fgetc(inputHandle)) != EOF)
    doSomethingWith(charInt);

Leave a Comment