使用 fread 读取文件时重复最后一个条目
我正在尝试读取4 字节块的二进制文件。然而,第一个实现(如下所示)将复制最后一个条目,并且仅复制最后一个条目。
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);
这个替代实现不存在这个问题。什么时候应该使用 feof?为什么之前的实现中的 feof 会导致最后一个条目被读取两次?有没有比像我在 printf 语句中所做的那样转换指针更好的方法来构造缓冲区?这段代码还有什么问题吗?
FILE* f = fopen("test.a", "r+b");
char buffer[4];
while (fread(buffer, 4, 1, f)) {
printf("read %x\n",*(int*)buffer);
}
fclose(f);
Possible Duplicates:
Why is this C code buggy?
Problem with EOF when determine stream end
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为一旦无法从文件中读取任何内容,就会在文件中设置 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的返回值:
成功读取的元素总数以size_t对象的形式返回。
所以你不是在寻找文件的结尾,如果最后一次读取拉回了任何内容,你会尝试再次读取。
Return Value of fread:
The total number of elements successfully read is returned as a size_t object.
So you're not looking for the end of the file, you try and read again if the last read pulled anything back.