1

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.

3
  • "Is there something like seekg that will go to a specific line in the text file? " - no. Commented May 12, 2018 at 20:06
  • mfw, I ended up doing the looping thing so I answered my own question lol Commented May 12, 2018 at 20:10
  • Possible duplicate of In C++ is there a way to go to a specific line in a text file? Commented May 12, 2018 at 20:26

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.