我想從C++的配置文件中讀取一些值,並且getline
似乎沒有工作。C++ ifstream 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());
}
消息功能是隻是一個包裝的printf和打印如下:
CONFIG: ./tool.conf
Exists?: true
Config is open: good
74181 Segmentation Fault: 11
但是,一切都在while循環被跳過。我正在閱讀的文件實際上也有數據。
爲什麼getline
即使文件存在並且可讀也不行?
UPDATE
我改變了上面的代碼,以反映卻被@rici建議的修改,現在我面臨着在while
循環任何事情之前在同一行段錯誤被調用。
你檢查,如果流是['好()'](http://www.cplusplus.com/reference/ios/ios/good /) – NathanOliver
@NathanOliver否我沒有和'good()'返回false – onetwopunch
getline()'不會工作,如果流是'!good()' – NathanOliver