gpt4 book ai didi

c++ - 如何知道指定的文件是否被正确读取?

转载 作者:行者123 更新时间:2023-11-27 23:19:20 24 4
gpt4 key购买 nike

为什么 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 不会在仍有任何 数据要读取时设置失败位。所以下面的标准循环 extracts all the lines :

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

// all done

关于c++ - 如何知道指定的文件是否被正确读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14430738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com