I had this snippet in a program (in Visual Studio 2005):
if(_eof(fp->_file))
{
break;
}
It broke the enclosing loop when eof was reached. But the program was not able to parse the last few thousand chars in file. So, in order to find out what was happening, I did this:
if(_eof(fp->_file))
{
cout<<ftell(fp)<<endl;
break;
}
Now the answer that I got from ftell was different (and smaller) than the actual file-size (which isn’t expected). I thought that Windows might have some problem with the file, then I did this:
if(_eof(fp->_file))
{
cout<<ftell(fp)<<endl;
fseek(fp, 0 , SEEK_END);
cout<<ftell(fp)<<endl;
break;
}
Well, the fseek() gave the right answer (equal to the file-size) and the initial ftell() failed (as previously told).
Any idea about what could be wrong here?
EDIT: The file is open in “rb” mode.
You can’t reliably use
_eof()on a file descriptor obtained from aFILE*, becauseFILE*streams are buffered. It means thatfphas suckedfp->_filedry and stores the remaining byte in its internal buffer. Eventuallyfp->_fileis at eof position, whilefpstill has bytes for you to read. Usefeof()after a read operation to determine if you are at the end of a file and be careful if you mix functions which operate onFILE*with those operating on integer file descriptors.