2011-12-21 140 views
1

可能重複:
In C++ is there a way to go to a specific line in a text file?如何 - 從文本文件中讀取特定的組線

請告訴我更聰明的方式來讀取特定組線(行號以行號B)從C++的文本文件中使用標準C++庫(不選擇Boost)?

+0

比什麼更聰明? – 2011-12-21 16:58:21

+0

而不是從開始讀取文件以匹配那些行號來提取文本..! – Vignesh 2011-12-21 17:01:27

+0

我假設它在逐行處理時手動計數行,只消耗從A到B的行 – minus 2011-12-21 17:02:28

回答

3

如果行長度不固定,並且沒有索引,則不能比計算\n更好。

考慮這個例子的文件:

Hello\nThis is a multi\n-line\nfile, where is this?\n\nAgain? 

行1點開始於字節0,第2行第6,第3行,在22,在28 4行,第5行,在49和6號線,在50 - 有沒有模式。

如果我們事先知道這些信息,例如在文件的開始,我們在某個表中獲得了這些信息,我們可以爲文件中的字節計算出我們所關心的行的字節偏移量,並使用搜索直接在那裏跳轉。

如果行寬度固定爲20個字節:

Hello    \nThis is a multi  \n-line    \nfile, where is this?\n     \nAgain? 

然後,我們可以計算線作爲一個簡單的乘法的開始 - 偏移到文件中。


如果您正在尋找這樣的一個「通用」的方式,我建議是這樣的:

#include <sstream> 
#include <fstream> 
#include <iostream> 
#include <algorithm> 
#include <string> 

template <typename Iter, typename Count, typename T> 
Iter find_nth(Iter it, const Iter end, Count c, const T match) { 
    while(c > 0 && it != end) { 
    if (match == *it++) 
     --c; 
    } 
    return it; 
} 

int main() { 
    std::ifstream in("test.txt"); 
    std::ostringstream str; 
    str << in.rdbuf(); 

    const std::string& s = str.str(); 
    const int A=2, B=4; 
    const std::string::const_iterator begin=find_nth(s.begin(),s.end(), A, '\n'); 
    const std::string::const_iterator end =find_nth(begin,s.end(), B-A, '\n'); 

    const std::string range(begin,end); 
    std::cout << range << std::endl; 
} 

這是適用於小十歲上下的文件(它讀取整個文件到一個std::string)。對於較大的文件,您可能需要做同樣的事情,但使用mmap而不是使用映射區域作爲迭代器。或者,您可以使用RandomAccess迭代器在文件中使用seek()。 (std::istream_iterator不這樣做,它只是一個ForwardIterator所以不適合)。

+0

非常感謝。 – Vignesh 2011-12-21 17:37:16

+0

@Vignesh - 我用一個例子更新了它。一種從A行和B行之間閱讀的通用方法。 – Flexo 2011-12-21 17:54:17

+0

我明白了,非常好,現在我必須嘗試使用​​地圖(適用於較大的文件)。再次,非常感謝。 – Vignesh 2011-12-21 21:40:56

0

好辦法,我認爲是計算的線和本安輸出你想要的線,我認爲更好的解決辦法是標籤,但嗯,這是我得到了它的工作,對不起我的noobieness:

在這例如我們要讀取包含「獅子座3」的3號線,噢,不要忘了,包括圖書館或標題:iostreamstringfstream

int count; 

string lines; 
ofstream FileC("file.txt",ios::app); 


lines = "Leo \nLeo2 \nLeo3 \n"; 
FileC << lines; 
FileC.close(); 

ifstream FileR("file.txt"); 

for(count = 1; count <= 3; count++) 
getline(FileR, lines); 

cout << lines << endl; 

而且如果u想使和if語句確保它有由於getline的工作方式,我認爲這個詞後面的空格:

if(lines == "Leo3 ") 
{ 
    cout << "Yay!"; 
} 
相關問題