2010-05-26 35 views
6

我正在使用以下代碼讀取文本文件中的行。處理線路大於SIZE_MAX_LINE限制的情況時,最佳方法是什麼?如何從C++的文本文件讀取長行?

void TextFileReader::read(string inFilename) 
{ 
    ifstream xInFile(inFilename.c_str()); 
    if(!xInFile){ 
     return; 
    } 

    char acLine[SIZE_MAX_LINE + 1]; 

    while(xInFile){ 
     xInFile.getline(acLine, SIZE_MAX_LINE); 
     if(xInFile){ 
      m_sStream.append(acLine); //Appending read line to string 
     } 
    } 

    xInFile.close(); 
} 
+0

其實我想知道如何處理eofbit和功能 – sonofdelphi 2010-05-26 07:34:11

+1

如果您使用std ::字符串你沒有需要測試的大小限制 – Nikko 2010-05-26 07:39:03

+0

failbit設置什麼那麼一條讀線的大小是多少? – sonofdelphi 2010-05-26 09:39:08

回答

10

請勿使用istream::getline()。它涉及裸體字符緩衝區,因此容易出錯。更好地利用std::getline(std::istream&,std::string&, char='\n')<string>頭:

std::string line; 

while(std::getline(xInFile, line)) { 
    m_sStream.append(line); 
    m_sStream.append('\n'); // getline() consumes '\n' 
} 
+0

這個怎麼樣? \t istream_iterator cursor(xInFile); \t istream_iterator endmarker; (遊標!=結束標記){ \t while(cursor!= endmarker) \t \t cursor ++; \t} – sonofdelphi 2010-05-26 09:32:17

+0

@sonofdelphi:IIUC,這將讀取_words_,而不是_lines_(其中「word」是由空白分隔的任何東西)。爲了讀取行,您必須使用讀取行的類型而不是單詞來實例化'std :: istream_iterator'。不應該很難想出這樣的類型,但在標準庫中沒有。 – sbi 2010-05-26 10:14:57

2

如果您使用字符串free function,你不必通過一個最大長度。它也使用C++字符串類型。

9

由於您已經使用C++和iostream,爲什麼不使用std::stringgetline function

std::string acLine; 
while(xInFile){ 
    std::getline(xInFile, acLine); 
    // etc. 
} 

而且,用xInFile.good()確保eofbitbadbitfailbit集。

+2

我只是做「while(std :: getline(xInFile,acLine)){}」 – Nikko 2010-05-26 07:39:41

+0

Kenny,當輸入失敗時,它會嘗試處理'//等'部分的舊數據。 (如果字符串是函數的本地字符串,它至少是一個空字符串。)更好地使用日光的成語。請參閱[我的答案](http://stackoverflow.com/questions/2910836/how-do-i-read-long-lines-from-a-text-file-in-c/2911350#2911350)。 – sbi 2010-05-26 08:44:11