使用 fread 读取文件时重复最后一个条目

发布于 2024-11-08 00:14:49 字数 805 浏览 6 评论 0原文

可能的重复:
为什么这段 C 代码有错误?
确定流结束时出现 EOF 问题

我正在尝试读取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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

慕巷 2024-11-15 00:14:49

这是因为一旦无法从文件中读取任何内容,就会在文件中设置 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.

你的往事 2024-11-15 00:14:49

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文