0

为什么在读取指定文件的最后一行后ifstream设置为failbit1如何知道指定的文件是否被正确读取?

bool read_csv_file(const char* filename, vector<string>& lines, bool adding = false)
{
    if( !adding ) lines.clear();

    ifstream csvfile;
    csvfile.open(filename);

    if( csvfile.is_open() )
    {
        string line;
        while( csvfile.good() && getline(csvfile,line) )
        {
            lines.push_back(line);
            cout << "fail: " << csvfile.fail() << endl;
        }
        cout << "fail: " << csvfile.fail() << endl;
        csvfile.close();
        return (!csvfile.fail());
    }

    return false;
}
4

3 回答 3

2

运行完文件末尾后会设置失败位。一旦发生这种情况,您就不能尝试解释输入操作的结果。不过,这很好,并且getline在仍有任何数据要读取时不会设置失败位。因此,以下标准循环提取所有

for (std::string line; std::getline(csvfile, line); )
{
    // process "line"
}

// all done
于 2013-01-20T23:54:02.790 回答
1

阅读最后一行(或任何一行)后可以设置的唯一原因failbit是库中是否有错误,我真的不相信。如果failbit已设置,则表示您没有阅读任何内容。在您的情况下,当您处于循环中时,它永远不会被设置;如果它被设置,getline将评估为false,并且您不会进入循环。当然,循环正是因为getline 失败而终止(或者会失败——通常,在输入之前你不会测试 ,如果你这样做了,不管测试是否失败,都good认为 已经设置了)。failbit

这类事情的通常模式是:

while ( someInput ) {
    //  ...
}
if ( csvfile.bad() ) {
    //  Serious error (disk read error, etc.)...
} else if ( ! csvfile.eof() ) {
    //  Formatting error...
} else {
    //  Normal end of file...
}

但是, When someInputisstd::getline()永远不会因为格式错误而失败,因此else if上述情况永远不会成立(许多代码将硬盘错误视为文件结尾,因此if也忽略了该部分)。

于 2013-01-21T00:20:58.620 回答
1

太检查错误读取,您必须badbit使用stream.bad().

Failbit表示操作逻辑失败,并且显然getline在达到 EOF 时设置它(在我的机器上确认)。

于 2013-01-21T00:04:23.520 回答