【发布时间】:2015-08-10 01:44:08
【问题描述】:
我正在尝试读取大小为 114,808 字节的二进制文件。我为文件分配内存,然后尝试使用fopen 和fread 读入文件。第一次调用 fread 时,它总是读取 274 个字节,随后对 feof 的调用总是返回 1,即使显然还没有到达文件末尾。这是为什么呢?
根据feof 的MSDN documentation,“如果读取操作试图读取文件末尾,则feof 函数返回非零值;否则返回0。”所以我不明白是什么导致feof 始终返回 1。
这是我目前拥有的代码。任何帮助将非常感激。谢谢!
// 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 );
}
仅供参考,我正在尝试编写此代码,以便源或多或少与 C 兼容,即使 MSVS 基本上强制您进入 C++ 环境。
【问题讨论】:
-
你不是在读取二进制文件;你正在阅读一个文本文件。使用
pFile = fopen(pSrcPath, "rb");打开二进制文件。可能发生的情况是有一个字节 0x1A 或 032 或 26 或 control-Z 使文本处理逻辑将其解释为 EOF。 -
"... 源代码或多或少与 C 兼容..." 要么兼容,要么不。没有“有点怀孕”。分配内存后,您必须做出决定。
标签: c++ c file-io visual-studio-2015 feof