在VS 2008 Express中,ifstream搜寻不返回eof吗? [英] ifstream seekg beyond end does not return eof in VS 2008 Express?

查看:82
本文介绍了在VS 2008 Express中,ifstream搜寻不返回eof吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VS 2005中,我有一些看起来像这样的代码:

In VS 2005, I have some code that looks like this:

ifs.open("foo");
while (!ifs.eof())
{
    ifs.read(&bar,sizeof(bar));
    loc = ifs.tellg();
    loc += bar.dwHeaderSize;
    // four byte boundary padding
    if ((loc % 4) != 0)
        loc += 4 - (loc % 4);
    ifs.seekg(loc,ios::beg);
}
ifs.close();

该代码在VS 2005中工作正常,但在VS 2008 Express中失败.据我所知,在代码查找到文件末尾之后,VS 2008不会返回eof().我想念什么吗?我通过添加显式检查以查看查找位置是否超出文件大小来修复此问题,但我想确保我正确理解了ifstream.

The code worked fine in VS 2005, but it fails in VS 2008 Express. From what I can tell, VS 2008 is not returning eof() after the code seeks to the end of the file. Am I missing something? I fixed it by adding an explicit check to see if the seek location exceeded the file size, but I want to be sure I understand ifstream correctly.

推荐答案

仅当您尝试读取文件末尾之后才触发EOF标志.
读取文件末尾的upto不会触发它.

The EOF flag is only triggered after you attempt to read past the end of file.
Reading upto the end of file will not trigger it.

这就是为什么大多数代码看起来像这样的原因:

This is why most code looks like this:

while(ifs.read(&bar,sizeof(bar)))
{
     // Do Stuff
}

如果read()的结果达到EOF,则将进入循环.
如果read()的结果超过了EOF,则不会陷入循环

If the result of the read() goes upto the EOF the loop will be entered.
If the result of the read() goes past the EOF the loop will NOT be enetered

  • 注意:如果文件中剩余零字节,则read()仅会超过EOF.否则它将读取到文件末尾.因此,如果文件中还剩东西,总是进入循环.

原因是读取的结果(返回值)是对流的引用.如果在布尔上下文(例如if测试表达式)中使用该流,则将其转换为可在此类上下文中使用的类型.转换的结果将测试EOF标志(以及其他几个标志),如果EOF为true,则返回等价的false.

The reason is the result of the read (the return value) is a reference to the stream. If the stream is used in a boolean context (such as the if test expression) it is converted into a type that can be used in such a context. The result of this conversion tests the EOF flag (in addition to a couple of others) and returns the quivalent of false if EOF is true.

注意:
如果您重载运算符<<对于您的Bar类,因为它应该准确地读取对象所需的内容,而不会超出EOF.这样就可以更轻松地使对象准确地读取到文件末尾而无需进行遍历.我担心read的事情是,如果read()想要10个字节,而文件中只有5个字节,那么对于部分填充的对象会发生什么?

Note:
This techniques works better if you overload the operator << for your Bar class as this should read in exactly what it needs for the object without going past the EOF. It is then easier to make your objects read exactly upto the end of the file without going over. The thing I worry about with read is what should happen if read() wants 10 bytesand there are only 5 bytes in the file, what happens with the partially filled object?

如果要继续使用样式,代码应如下所示:

If you want to continue using your style the code should look like this:

ifs.open("foo");
while (!ifs.eof())
{
    ifs.read(&bar,sizeof(bar));
    if (ifs.eof())
    {    break;
    }
    // Do Stuff
}

这篇关于在VS 2008 Express中,ifstream搜寻不返回eof吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆