Reputation: 655
I'm currently trying to read in a PNG file, one byte at a time, and I'm getting different results when I use fread((void*), size_t, size_t, FILE*)
and fgetc(FILE*)
.
I essentially want to "Read one byte at a time until the file ends", and I do so in two different ways. In both cases, I open the image I want in binary mode through:
FILE* input = fopen( /* Name of File */, 'rb');
And store each byte in a character, char c
fread: while( fread(&c, 1, 1, input) != 0) //read until there are no more bytes read
fgetc:
while( (c = fgetc(input)) != EOF) //Read while EOF hasn't been reached
In the fread
case, I read all the bytes I need to do. The reading function stops at the end of the file, and I end up printing all 380,000 bytes (which makes sense, as the input file is a 380kB file).
However, in the fgetc
case, I stop once I reach a byte with a value of ff
(which is -1, the value of the macro EOF
.
My question is, if both functions are doing the same thing, reading one byte at a time, how does fread know to continue reading even if it comes across a byte with a value of EOF
? And building off of this, how does fread know when to stop if EOF
is passed when reading the file?
Upvotes: 0
Views: 1075
Reputation: 241701
fgetc
returns an int
, not a char
. EOF
(and many actual character codes) cannot be stored in a char
and attempting to do so will result in Undefined Behaviour. So don't do that. Store the return value in an int
.
Upvotes: 4