C语言 fread 如何知道 C 中的文件何时结束?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15697783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:52:35  来源:igfitidea点击:

How does fread know when the file is over in C?

cfile-iofread

提问by user202925

So I'm not entirely sure how to use fread. I have a binary file in little-endian that I need to convert to big-endian, and I don't know how to read the file. Here is what I have so far:

所以我不完全确定如何使用 fread。我有一个小端二进制文件,我需要将其转换为大端,但我不知道如何读取该文件。这是我到目前为止所拥有的:

FILE *in_file=fopen(filename, "rb");
char buffer[4];
while(in_file!=EOF){
    fread(buffer, 4, 1, in_file);
    //convert to big-endian.
    //write to output file.
}

I haven't written anything else yet, but I'm just not sure how to get fread to 'progress', so to speak. Any help would be appreciated.

我还没有写任何其他东西,但我只是不知道如何让恐惧“进步”,可以这么说。任何帮助,将不胜感激。

回答by Mohamad Ali Baydoun

That's not how you properly read from a file in C.

这不是您正确读取 C 文件的方式。

freadreturns a size_trepresenting the number of elements read successfully.

fread返回一个size_t代表成功读取的元素数。

FILE* file = fopen(filename, "rb");
char buffer[4];

if (file) {
    /* File was opened successfully. */

    /* Attempt to read */
    while (fread(buffer, 1, 4, file) == 4) {
        /* byte swap here */
    }

    fclose(file);
}

As you can see, the above code would stop reading as soon as freadextracts anything other than 4 elements.

如您所见,只要fread提取了 4 个元素以外的任何内容,上面的代码就会停止读取。