简体   繁体   中英

Reading specific lines from a file in C++

The following code is meant to loop through the last ten lines of a file that I have previously opened. I think the seekg function refers to binary files and only go through individual bytes of data, so that may be my issue here.

    //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;
}

The other method I was thinking of doing is just counting the number of times the file gets looped through initially, taking that and subtracting ten, then counting through the file that number of times, then outputting the next ten, but that seems extensive for what I want to do.

Is there something like seekg that will go to a specific line in the text file? Or should I use the method I proposed above?

EDIT: I answered my own question: the looping thing was like 6 more lines of code.

向后搜索换行符10次,或直到文件光标小于或等于零为止。

If you don't care about the order of the last 10 lines, you can do this:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM