I'm trying to read in a binary file of size 114,808 bytes. I allocate memory for the file, and then try to read in the file using fopen
and fread
. The first time fread
is called, it always reads in 274 bytes, and the subsequent call to feof
always returns 1, even though clearly the end of the file has not been reached. Why is this?
According to the MSDN documentation for feof
, "The feof function returns a nonzero value if a read operation has attempted to read past the end of the file; it returns 0 otherwise." So I don't understand what is causing feof
to consistently return 1.
Here's the code that I have so far. Any help would be much appreciated. Thanks!
// Open source file with read-only access
if ( iError == ERROR_SUCCESS )
{
#ifdef _MSC_VER
#pragma warning(disable : 4996)
#endif
pFile = fopen( pSrcPath, "r" );
if ( pFile == NULL )
{
iError = ERROR_FILE_NOT_FOUND;
}
}
// Read in source file to memory
if ( iError == ERROR_SUCCESS )
{
do
{
// Buffer pointer passed to fread will be the file buffer, plus the
// number of bytes actually read thus far.
iSize = fread( pFileBuf + iActReadSz, 1, iReqReadSz, pFile );
iError = ferror( pFile ); // check for error
iEndOfFile = feof( pFile ); // check for end of file
if ( iError != 0 )
{
iError = ERROR_READ_FAULT;
}
else if ( iEndOfFile != 0 )
{
// Read operation attempted to read past the end of the file.
fprintf( stderr,
"Read operation attempted to read past the end of the file. %s: %s\n",
pSrcPath, strerror(errno) );
}
else
{
iError = ERROR_SUCCESS; // reset error flag
iActReadSz += iSize; // increment actual size read
iReqReadSz -= iSize; // decrement requested read size
}
}
while ((iEndOfFile == 0) && (iError == ERROR_SUCCESS));
}
// Close source file
if ( pFile != NULL )
{
fclose( pFile );
}
FYI, I'm trying to write this, so that the source is more-or-less compatible with C, even though MSVS basically forces you into a C++ environment.
You didn't include "b" in the mode string for fopen. On MS Windows, opening a file in text mode will result in (among other things that you don't usually want happening when reading a binary file) it detecting an EOF whenever it reaches a byte with the value 0x1A.