使用fread读取文件时复制最后一个条目 [英] Duplicate last entry when reading a file using fread

查看:295
本文介绍了使用fread读取文件时复制最后一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<强>可能显示的文件:结果,
这是为什么C代码车?结果,
确定流结束时的问题EOF

Possible Duplicates:
Why is this C code buggy?
Problem with EOF when determine stream end

试图以4字节块读取二进制文件。然而,第一个实现(如下所示)将复制最后一个条目,并只复制最后一个条目。

I'm trying to read a binary file in 4 byte chunks. However the first implementation (shown below) will duplicate the last entry and only the last entry.

FILE* f = fopen("test.a", "r+b");
char buffer[4];
while (!feof(f)) {
    fread(buffer, 4, 1, f);
    printf("read %x\n",*(int*)buffer);
}
fclose(f);

这个替代实现没有这个问题。什么时候应该使用?为什么在前面的实现中导致最后一个条目被读两次呢?有没有更好的方法来构建缓冲区,而不是像在printf语句中那样投射指针?这段代码还有什么不对吗?

This alternative implementation does not have that issue. When should feof be used? And why is feof in the previous implementation causing the last entry to be read twice? Is there a better way to construct the buffer than casting the pointer as I have done in the printf statement? Is there anything else wrong with this code?

FILE* f = fopen("test.a", "r+b");
char buffer[4];
while (fread(buffer, 4, 1, f)) {
    printf("read %x\n",*(int*)buffer);
}
fclose(f);


推荐答案

这是因为在EOF标志的文件中设置的一旦什么都不是可以从中读取。这会导致最后一个 fread 读取some,但不会建立eof标记。然后,下一个循环 fread 将不会读取任何内容,然后在文件中设置eof标记。由于fread并没有改变缓冲区,所以你在最后一行打印两次。

This is because the eof mark is set in the file once nothing can be read from it. This causes the last fread to read "some", but not stablishing the eof mark. Then, the next loop, fread will read nothing, and then cause the eof mark to be set in the file. As fread has not changed the buffer, you have in it the last line, printed twice.

这篇关于使用fread读取文件时复制最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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