2015-05-14 54 views
0

我想從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循環任何事情之前在同一行段錯誤被調用。

+1

你檢查,如果流是['好()'](http://www.cplusplus.com/reference/ios/ios/good /) – NathanOliver

+0

@NathanOliver否我沒有和'good()'返回false – onetwopunch

+0

getline()'不會工作,如果流是'!good()' – NathanOliver

回答

7

您打開config兩次(一次在構造函數中,再次使用明確的open)。第二個open是一個錯誤,導致失敗位置位(即使ifstream仍處於打開狀態)。從此,對ifstream的所有I/O操作都將失敗。

+0

非常感謝!剛剛註釋掉了第二個開放,現在它的工作原理...以及我現在得到一個seg錯誤,但至少有一個不同的問題:) – onetwopunch

+0

只注意到seg錯誤發生在while循環中的第一個打印語句之前。任何想法可能是什麼原因造成的? – onetwopunch

+0

@jryancanty:顯然'Message'已損壞。你可能做錯了可變參數。 –

0

您打開同一個文件兩次 刪除
config.open(configPath);


if (config.is_open())