提问人:Jim Fell 提问时间:8/10/2015 更新时间:8/10/2015 访问量:350
函数 'feof' 始终返回 1 [duplicate]
Function `feof` Always Returns 1 [duplicate]
问:
我正在尝试读取大小为 114,808 字节的二进制文件。我为文件分配内存,然后尝试使用 和 读取文件。第一次调用时,它总是以 274 个字节读取,随后的调用总是返回 1,即使显然尚未到达文件末尾。为什么会这样?fopen
fread
fread
feof
根据 MSDN 文档,“如果读取操作尝试读取文件末尾,则 feof 函数返回非零值;否则返回 0。所以我不明白是什么导致持续返回 1。feof
feof
这是我目前拥有的代码。任何帮助将不胜感激。谢谢!
// 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++ 环境。
答:
7赞
Random832
8/10/2015
#1
您没有在 fopen 的模式字符串中包含“b”。在 MS Windows 上,以文本模式打开文件将导致(除其他您在读取二进制文件时通常不希望发生的事情外)每当它到达值为 0x1A 的字节时,它就会检测到 EOF。
评论
pFile = fopen(pSrcPath, "rb");