[英]How do I know if the specified file has been read correctly?
在读取指定文件的最后一行后, ifstream
为什么将failbit
设置为1
? 我如何知道是否已正确读取指定的文件?
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;
}
在您结束文件末尾后,将设置失败位。 一旦发生这种情况,您就不必尝试解释输入操作的结果。 不过,这很好,并且在仍然有任何数据要读取的情况下, getline
不会设置失败位。 因此,以下标准循环提取了所有行 :
for (std::string line; std::getline(csvfile, line); )
{
// process "line"
}
// all done
太要检查错误的读取,您必须使用stream.bad()
测试badbit
。
Failbit
表示操作逻辑失败,显然getline
在到达EOF时对其进行了设置(在我的机器上已确认)。
读取最后一行(或任何一行)后可以设置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...
}
但是,当someInput
为std::getline()
时,您将永远不会因为格式错误而失败,因此else if
以上内容将永远不成立(并且许多代码将硬盘错误视为文件结尾,因此也忽略了if
部分)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.