C++ ifstream错误检查

slo*_*red 21 c++ error-handling ifstream

我是C++的新手,想要为我的代码添加错误检查,我想确保我使用良好的编码实践.我使用以下命令将ASCII文件中的一行读入字符串:

ifstream paramFile;
string tmp;

//open input file

tmp.clear();

paramFile >> tmp;

//parse tmp
Run Code Online (Sandbox Code Playgroud)
  1. 如何进行错误检查以确保输入文件读取成功?

  2. 我看到从那里读取ASCII文件的更复杂的方法.我这样做的方式是"安全/健壮"吗?

Jes*_*ood 13

paramFile >> tmp;如果该行包含空格,则不会读取整行.如果你想要那个std::getline(paramFile, tmp);读取直到换行的用法.通过检查返回值来完成基本错误检查.例如:

if(paramFile>>tmp) // or if(std::getline(paramFile, tmp))
{
    std::cout << "Successful!";
}
else
{
    std::cout << "fail";
}
Run Code Online (Sandbox Code Playgroud)

operator>>并且std::getline都返回对流的引用.流评估为布尔值,您可以在读取操作后检查该值.如果读取成功,上面的示例将仅评估为true.

以下是我如何制作代码的示例:

ifstream paramFile("somefile.txt"); // Use the constructor rather than `open`
if (paramFile) // Verify that the file was open successfully
{
    string tmp; // Construct a string to hold the line
    while(std::getline(paramFile, tmp)) // Read file line by line
    {
         // Read was successful so do something with the line
    }
}
else
{
     cerr << "File could not be opened!\n"; // Report error
     cerr << "Error code: " << strerror(errno); // Get some info as to why
}
Run Code Online (Sandbox Code Playgroud)

  • 假设文件已经打开(成功).接下来,我成功地阅读了一些数据.但不幸的是有人用我的文件删除了软盘驱动器.我试图从OS系统调用中读取和接收IOerror.那么,我怎么能发现这种情况呢?换句话说,我们应该区分EOF和IOError.std :: getline返回流.流上的operator bool返回"!stream-> fail()".但是在eof上,failbit也设置了...所以逻辑变成了噩梦.(请参阅http://www.cplusplus.com/reference/ios/ios/fail上的表格)并注意,尝试读取EOF的流也设置了failbit.AAAAAAA :( (3认同)