C ++ ifstream getline无效

时间:2015-05-14 17:43:17

标签: c++ fstream

我试图用c ++中的配置文件读取一些值,getline似乎无法正常工作。

代码的相关部分如下所示:

#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std;
// ...
ifstream config( configPath );
  string line;

  Message( DiagVerbose, "CONFIG: %s\n", configPath.c_str());
  bool exists = ( access( configPath.c_str(), F_OK && R_OK ) != -1 );
  Message( DiagVerbose, "Exists?: %s\n", exists ? "true" : "false");

  // This was causing a fail bit to set 
  //config.open( configPath );
  if (config.is_open())
  {
    Message( DiagVerbose, "Config is open%s\n", config.good() ? "good" : "bad" );
    while ( getline( config, line ) )
    {
      Message( DiagVerbose, "Line: %s", line.c_str());
      extension_t extension = parseConfig( line );
      extensions[ extension.name ] = extension.type;
    }
    config.close();
  } else {
    FatalError( "Could not open file %s\n", configPath.c_str());
  }

Message函数只是printf的包装器并打印以下内容:

CONFIG: ./tool.conf
Exists?: true
Config is open: good
74181 Segmentation Fault: 11

但是跳过了while循环中的所有内容。我读取的文件实际上也有数据。

为什么即使文件存在且可读,getline也没有获取该行?

更新

我更改了上面的代码以反映@rici建议的更改,但是现在我在调用while循环中的任何内容之前在同一行遇到了分段错误。

2 个答案:

答案 0 :(得分:7)

您打开config两次(一次在构造函数中,再次使用显式open)。第二个open是一个错误,它会导致设置failbit(即使ifstream仍处于打开状态。)从那时起,对ifstream的所有I / O操作都将失败。

答案 1 :(得分:0)

您打开两次相同的文件 取下
config.open( configPath );

之前
if (config.is_open())