2012-10-15 24 views
5

當我使用ifstream從文件中讀取一行後,是否有辦法讓流回到我剛剛讀取的行的開頭,有條件?如何將ifstream返回到剛剛用C++讀取的行的開頭?

using namespace std; 
//Some code here 
ifstream ifs(filename); 
string line; 
while(ifs >> line) 
{ 
    //Some code here related to the line I just read 

    if(someCondition == true) 
    { 
    //Go back to the beginning of the line just read 
    } 
    //More code here 
} 

因此,如果someCondition爲true,則在下一個while循環迭代過程中讀取的下一行將與我剛剛閱讀的行相同。否則,下一個while循環迭代將在文件中使用以下行。如果您需要進一步澄清,請不要猶豫,問。提前致謝!

更新#1

所以我試過如下:

while(ifs >> line) 
{ 
    //Some code here related to the line I just read 
    int place = ifs.tellg(); 
    if(someCondition == true) 
    { 
    //Go back to the beginning of the line just read 
    ifs.seekg(place); 
    } 
    //More code here 
} 

但是,當條件爲真它不會再次讀取同一行。整數是可接受的類型嗎?

更新#2:解決方案

有我的邏輯錯誤。這是因爲我希望它對於任何那些好奇的作品修正版本:

int place = 0; 
while(ifs >> line) 
{ 
    //Some code here related to the line I just read 

    if(someCondition == true) 
    { 
    //Go back to the beginning of the line just read 
    ifs.seekg(place); 
    } 
    place = ifs.tellg(); 
    //More code here 
} 

的調用所以tellg()被轉移到年底,因爲你需要尋求先前閱讀的開始線。我第一次調用tellg(),然後在流更改之前調用seekg(),這就是爲什麼它沒有任何改變(因爲它沒有改變)。謝謝大家的貢獻。

+1

使用tellg()在讀取該行之前獲取流位置並seekg()將流位置設置爲之前保存的位置。 –

+1

順便說一下,ifs >>到字符串不是獲取行,而是字。使用std :: getline –

+0

感謝您關注getline。它可能會在未來造成惱人的錯誤。 –

回答

3

沒有直接的方式來表達 「找回最後一行的開始」。但是,您可以使用std::istream::tellg()回到您保留的位置。也就是說,在閱讀一條線之前,您需要使用tellg(),然後使用seekg()返回該位置。

但是,經常調用搜索函數相當昂貴,也就是說,我會考慮刪除再次讀取行的要求。

+0

謝謝。效率並不是我的直接擔憂,但我會嘗試稍後研究其他一些方法。現在我的主要焦點是獲得一些有用的東西。 –

+0

我需要從函數中的40GB文件中讀取字符,直到找到該函數不應讀取的字符(分隔字符)。使用peek()更便宜或tellg()seekg()來標記之前的字符位置,我需要返回到?我想最有效率的方法是不使用任何這個,只返回額外的讀字符。 – bkarj

+0

@BehroozKarjoo:使用'peek()'相當便宜。本質上它會返回this-> gptr()!= this-> egptr()? * this-> gptr():this-> underflow();'(儘管將char'正確地擴展爲'int')。假設流被緩衝,這是一個指針比較和取消引用。一個'peek()'調用可以做更多的工作。 –

相關問題