C++ ifstream getline 不工作

C++ ifstream getline not working

我正在尝试从 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 循环中的任何内容之前在同一行面临分段错误。

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

您打开同一个文件两次 删除
config.open( configPath );

之前
if (config.is_open())