简体   繁体   中英

Difference between fread(&c, 1, 1, input) and fgetc(input) for reading one byte

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM