C++ ifstream getline不能正常工作

one*_*nch 0 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());
  }
Run Code Online (Sandbox Code Playgroud)

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

CONFIG: ./tool.conf
Exists?: true
Config is open: good
74181 Segmentation Fault: 11
Run Code Online (Sandbox Code Playgroud)

但是跳过了while循环中的所有内容.我正在读取的文件确实包含数据.

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

UPDATE

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

ric*_*ici 7

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