feof()
seems to return 0
after reading the last byte of the file. It returns 1
after fgetc()
already made the attempt to read one more byte after the end of the file.
When fgetc()
makes the attempt to read data after the end of the file, fgetc()
returns -1
.
If you perform fputc(x, ...)
and x
is not in the range 0...255
, fputc()
will actually write the byte (x & 0xFF)
.
On nearly all modern computers, (-1 & 0xFF)
is 0xFF
which equals the character 'ÿ'
.
So the following happens:
- ...
- Your program reads the last byte of the file using
fgetc()
- It writes that character using
fputc()
- Although there are no more bytes left in the file,
feof()
returns 0
because you did not make the attempt to read bytes after the end of the file, yet.
- Your program calls
fgetc()
and because there are no more bytes left, fgetc()
returns -1
.
- Your program calls
fputc(-1, ...)
which writes the character 'ÿ'
.
feof()
returns 1
because fgetc()
already tried to read bytes after the end of the file.