簡體   English   中英

從C ++文件中讀取特定行

[英]Reading specific lines from a file in C++

以下代碼旨在遍歷我先前打開的文件的最后十行。 我認為seekg函數引用二進制文件,並且僅處理單個字節的數據,因此這可能是我的問題。

    //Set cursor to 10 places before end
    //Read lines of input
    input.seekg(10L, ios::end);

    getline(input, a);

    while (input) {
        cout << a << endl;
        getline(input, a);
    }

    input.close();
    int b;
    cin >> b;
    return 0;
}

我想做的另一種方法是只計算文件最初循環通過的次數,將其減去十次,然后遍歷文件該次數,然后輸出下一個十次,但這似乎很廣泛我想要做。

是否有類似seekg內容會轉到文本文件中的特定行? 還是應該使用上面建議的方法?

編輯:我回答了我自己的問題:循環的事情就像6多行代碼。

向后搜索換行符10次,或直到文件光標小於或等於零為止。

如果您不關心最后10行的順序,則可以執行以下操作:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

int main() {

    std::ifstream file("test.txt");
    std::vector<std::string> lines(10);

    for ( int i = 0; getline(file, lines[i % 10]); ++i );

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM