首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数‘`feof`’总是返回1

函数‘`feof`’总是返回1
EN

Stack Overflow用户
提问于 2015-08-10 01:44:08
回答 1查看 314关注 0票数 0

我正在尝试读取一个大小为114,808字节的二进制文件。我为文件分配内存,然后尝试使用fopenfread读取文件。第一次调用fread时,它总是以274个字节读取,而后续对feof的调用总是返回1,尽管文件的结尾显然还没有到达。为什么会这样呢?

根据MSDN文档 for feof,“如果读取操作试图在文件结束后读取,则feof函数返回非零值;否则返回0”。因此,我不明白是什么原因导致feof始终返回1。

这是我到目前为止掌握的代码。任何帮助都将不胜感激。谢谢!

代码语言:javascript
复制
// 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,我试图写这个,这样源代码就可以或多或少地与C兼容,即使MSVS基本上强迫你进入一个C++环境。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-10 01:46:40

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

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31910583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档