开发者

Duplicate last entry when reading a file using fread [duplicate]

This question already has answers here: 开发者_Go百科 Closed 11 years ago.

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜