In C++ is there a way to go to a specific line in a text file?

Jim picture Jim · Mar 6, 2011 · Viewed 96.9k times · Source

If I open a text file using fstream is there a simple way to jump to a specific line, such as line 8?

Answer

Xeo picture Xeo · Mar 6, 2011

Loop your way there.

#include <fstream>
#include <limits>

std::fstream& GotoLine(std::fstream& file, unsigned int num){
    file.seekg(std::ios::beg);
    for(int i=0; i < num - 1; ++i){
        file.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    }
    return file;
}

Sets the seek pointer of file to the beginning of line num.

Testing a file with the following content:

1
2
3
4
5
6
7
8
9
10

Testprogram:

int main(){
    using namespace std;
    fstream file("bla.txt");

    GotoLine(file, 8);

    string line8;
    file >> line8;

    cout << line8;
    cin.get();
    return 0;
}

Output: 8