views:

90

answers:

1

Hey; I am reading a binary file. and when it reaches the end. it seems it is terminated by feof() function. is it because there is no EOF character for binary files? if so how can i solve it.

currently my code is using a while loop

while (!feof(f))

when it reaches the end of file at position 5526900. it doesn't stop. it just keeps trying to read, and i am stuck at the loop.

can anyone tell me why and how to solve it.

Thanks

+14  A: 

You should not use feof() to loop on - instead, use the return value of fread() - loop until it returns zero. This is easy to see if you consider reading an empty file - feof() returns the EOF status AFTER a read operation, so it will always try to read bogus data if used as a loop control.

I don't know why so many people think feof() (and the eof() member of C++ streams) can predict if the next read operation will succeed, but believe me, they can't.

anon
++ good catch, Neil
Eli Bendersky
thanks. it is functional as expected now . thank you Neil.
Grey