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