【问题标题】:C++ ifstream Error CheckingC++ ifstream 错误检查
【发布时间】:2012-11-06 22:47:12
【问题描述】:

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

ifstream paramFile;
string tmp;

//open input file

tmp.clear();

paramFile >> tmp;

//parse tmp
  1. 如何进行错误检查以确保输入文件读取成功?

  2. 我看到了从 ASCII 文件中读取的更复杂的方法。我这样做的方式“安全/稳健”吗?

【问题讨论】:

  • std::string 的默认构造函数生成一个空字符串。不需要clear()。另外,如果你想要一条线,请使用std::getline
  • 感谢链接亮度

标签: c++ error-handling ifstream


【解决方案1】:

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

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

operator&gt;&gt;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
}

【讨论】:

  • 谢谢杰西。我不知道您可以将流评估为布尔值。很有帮助!
  • 是的,所有流都有这个,因为它们从 std::basic_ios 继承它。这是reference
  • 伟大的参考杰西!我还没有找到那个。谢谢!
  • 嘿!当文件已经打开时你不检查 IO 错误(!)如何正确地做到这一点?
  • 假设文件已经打开(成功)。接下来,我成功读取了一些数据。但不幸的是,有人用我的文件删除了软盘驱动器。我没有尝试从操作系统系统调用读取和接收 IOerror。那么,我怎样才能检测到这种情况呢?换句话说,我们应该区分EOF和IOError。 std::getline 返回流。流上的运算符 bool 返回“!stream->fail()”。但是在 eof failbit 上也设置了......所以逻辑变成了噩梦。 (参见cplusplus.com/reference/ios/ios/fail 的表格),另外,请注意,尝试读取位于 EOF 的流也会设置故障位。 AAAAAAA :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 2013-05-11
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多