函数 'feof' 始终返回 1 [duplicate]

Function `feof` Always Returns 1 [duplicate]

提问人:Jim Fell 提问时间:8/10/2015 更新时间:8/10/2015 访问量:350

问:

我正在尝试读取大小为 114,808 字节的二进制文件。我为文件分配内存,然后尝试使用 和 读取文件。第一次调用时,它总是以 274 个字节读取,随后的调用总是返回 1,即使显然尚未到达文件末尾。为什么会这样?fopenfreadfreadfeof

根据 MSDN 文档,“如果读取操作尝试读取文件末尾,则 feof 函数返回非零值;否则返回 0。所以我不明白是什么导致持续返回 1。feoffeof

这是我目前拥有的代码。任何帮助将不胜感激。谢谢!

// 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++ 环境。

C++ C 文件-IO visual-studio-2015 feof

评论

1赞 Jonathan Leffler 8/10/2015
您不是在读取二进制文件;您正在阅读文本文件。用 打开二进制文件。可能发生的情况是,有一个字节 0x1A 或 032 或 26 或 control-Z 使文本处理逻辑将其解释为 EOF。pFile = fopen(pSrcPath, "rb");
0赞 too honest for this site 8/10/2015
"...source 或多或少与 C 兼容......”它要么兼容,要么兼容。没有“有点怀孕”。分配内存后,您将不得不做出决定。

答:

7赞 Random832 8/10/2015 #1

您没有在 fopen 的模式字符串中包含“b”。在 MS Windows 上,以文本模式打开文件将导致(除其他您在读取二进制文件时通常不希望发生的事情外)每当它到达值为 0x1A 的字节时,它就会检测到 EOF。