Visual Studio 中 EOF 在 EOF 之前

发布于 2024-12-02 09:31:59 字数 653 浏览 0 评论 0原文

我在一个程序(在 Visual Studio 2005 中)中有这个片段:

if(_eof(fp->_file))
{
    break;
}

当达到 eof 时,它打破了封闭循环。但该程序无法解析文件中的最后几千个字符。因此,为了找出发生了什么,我这样做了:

if(_eof(fp->_file))
{
    cout<<ftell(fp)<<endl;
    break;
}

现在我从 ftell 得到的答案与实际文件大小不同(并且更小)(这不是预期的)。我认为 Windows 可能对文件有一些问题,然后我这样做了:

if(_eof(fp->_file))
{
    cout<<ftell(fp)<<endl;
    fseek(fp, 0 , SEEK_END);
    cout<<ftell(fp)<<endl;
    break;
}

嗯,fseek() 给出了正确的答案(等于文件大小),并且初始 ftell() 失败了(如前所述)。

知道这里可能出什么问题吗?

编辑: 文件以“rb”模式打开。

I had this snippet in a program (in Visual Studio 2005):

if(_eof(fp->_file))
{
    break;
}

It broke the enclosing loop when eof was reached. But the program was not able to parse the last few thousand chars in file. So, in order to find out what was happening, I did this:

if(_eof(fp->_file))
{
    cout<<ftell(fp)<<endl;
    break;
}

Now the answer that I got from ftell was different (and smaller) than the actual file-size (which isn't expected). I thought that Windows might have some problem with the file, then I did this:

if(_eof(fp->_file))
{
    cout<<ftell(fp)<<endl;
    fseek(fp, 0 , SEEK_END);
    cout<<ftell(fp)<<endl;
    break;
}

Well, the fseek() gave the right answer (equal to the file-size) and the initial ftell() failed (as previously told).

Any idea about what could be wrong here?

EDIT: The file is open in "rb" mode.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巾帼英雄 2024-12-09 09:31:59

您无法在从 FILE* 获取的文件描述符上可靠地使用 _eof(),因为 FILE* 流已被缓冲。这意味着 fp 已经吸干了 fp->_file 并将剩余字节存储在其内部缓冲区中。最终 fp->_file 位于 eof 位置,而 fp 仍然有字节可供读取。在读取操作之后使用 feof() 来确定是否位于文件末尾,如果混合操作 FILE* 以及对整数文件描述符进行操作的代码。

You can't reliably use _eof() on a file descriptor obtained from a FILE*, because FILE* streams are buffered. It means that fp has sucked fp->_file dry and stores the remaining byte in its internal buffer. Eventually fp->_file is at eof position, while fp still has bytes for you to read. Use feof() after a read operation to determine if you are at the end of a file and be careful if you mix functions which operate on FILE* with those operating on integer file descriptors.

挽清梦 2024-12-09 09:31:59

如果您的文件 I/O 操作位于包装描述符的 FILE 流上,则不应直接在描述符上使用 _eof()。在应用程序从 FILE 流中读取所有数据之前,会发生缓冲,并且底层描述符将到达文件末尾。

在这种情况下,ftell(fp) 正在报告流的状态,您应该使用 feof(fp) 将它们保持在同一 I/O 域中。

You should not be using _eof() directly on the descriptor if your file I/O operations are on the FILE stream that wraps it. There is buffering that takes place and the underlying descriptor will hit end-of-file before your application has read all the data from the FILE stream.

In this case, ftell(fp) is reporting the state of the stream and you should be using feof(fp) to keep them in the same I/O domain.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文