如何FREAD知道该文件是在用C? [英] How does fread know when the file is over in C?

查看:125
本文介绍了如何FREAD知道该文件是在用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我不完全知道如何使用FREAD。我在小尾数的二进制文件,我需要转换为大端,我不知道如何读文件。以下是我迄今为止:

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:

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.
}

我没有写任何东西,但我只是不知道如何让FREAD以进步,可以这么说。任何帮助将是AP preciated。

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.

推荐答案

这不是你如何正确地从在C文件中读取。

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

FREAD 返回为size_t 重新presenting元素的数量成功读取。

fread returns a size_t representing the number of elements read successfully.

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);
}

正如你所看到的,上面code将停止只要 FREAD 提取物比4的元素以外的任何阅读。

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

这篇关于如何FREAD知道该文件是在用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆