简体   繁体   English

fread(&c,1,1,input)和fgetc(input)之间的区别,用于读取一个字节

[英]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*) . 我目前正在尝试一次读取一个PNG文件,并且在使用fread((void*), size_t, size_t, FILE*)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 并将每个字节存储在一个字符char c

fread: while( fread(&c, 1, 1, input) != 0) //read until there are no more bytes read 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 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. fread情况下,我读取了我需要做的所有字节。 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). 读取功能在文件末尾停止,我最终打印了所有380,000字节(这很有意义,因为输入文件是380kB文件)。

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 . 但是,在fgetc情况下,一旦到达值ff (即-1,即宏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 ? 我的问题是,如果两个函数都在做相同的事情,一次读取一个字节,即使fread遇到一个带有EOF值的字节,fread如何知道继续读取? And building off of this, how does fread know when to stop if EOF is passed when reading the file? 并以此为基础,读取文件时如果通过EOF ,fread如何知道何时停止?

fgetc returns an int , not a char . fgetc返回一个int ,而不是一个char EOF (and many actual character codes) cannot be stored in a char and attempting to do so will result in Undefined Behaviour. EOF (以及许多实际的字符代码)无法存储在char ,尝试这样做会导致未定义的行为。 So don't do that. 所以不要那样做。 Store the return value in an int . 将返回值存储在int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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