Louis Pelletier
Louis Pelletier

Reputation: 31

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.

Upvotes: 1

Views: 171

Answers (2)

DimChtz
DimChtz

Reputation: 4333

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

Upvotes: 0

James Poag
James Poag

Reputation: 2380

Search backwards for the newline character 10 times or until the file cursor is less than or equal to zero.

Upvotes: 2

Related Questions