[英]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());
}
消息功能只是printf的包裝器,它會打印以下內容:
CONFIG: ./tool.conf
Exists?: true
Config is open: good
74181 Segmentation Fault: 11
但是while循環中的所有內容都會被跳過。 另外,我正在讀取的文件中確實有數據。
為什么即使文件存在且可讀, getline
無法獲取該行?
更新
我更改了上面的代碼以反映@rici建議的更改,但是,現在在調用while
循環中的任何內容之前,我在同一行遇到Segmentation Fault。
您將config
兩次打開(一次在構造函數中,然后再次使用顯式open
)。 第二次open
是一個錯誤,它將導致設置故障位(即使ifstream仍處於打開狀態)。從那時起,對ifstream
所有I / O操作都會失敗。
您兩次打開相同的文件
config.open( configPath );
之前
if (config.is_open())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.