简体   繁体   中英

EOF before EOF in Visual Studio

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 a FILE* , because FILE* streams are buffered. It means that fp has sucked fp->_file dry and stores the remaining byte in its internal buffer. Eventually fp->_file is at eof position, while fp still has bytes for you to read. Use feof() after a read operation to determine if you are at the end of a file and be careful if you mix functions which operate on FILE* with those operating on integer file descriptors.

You should not be using _eof() directly on the descriptor if your file I/O operations are on the FILE stream that wraps it. There is buffering that takes place and the underlying descriptor will hit end-of-file before your application has read all the data from the FILE stream.

In this case, ftell(fp) is reporting the state of the stream and you should be using feof(fp) to keep them in the same I/O domain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM