Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top