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

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


Solution 1:

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

Solution 2:

If every line has the same length then you can use istream::seekg() to jump to the location and read from there.

Solution 3:

Here is a working and neat example with std::getline() if the lines have the same length:

#include <iostream>
#include <fstream>
#include <string>

const int LINE = 4;

int main() {
std::ifstream f("FILE.txt");
std::string s;

for (int i = 1; i <= LINE; i++)
        std::getline(f, s);

std::cout << s;
return 0;
}

Solution 4:

In general, no, you have to walk down using a strategy similar to what Xeo shows.

If as netrom says you know the lines have fixed length, yes.

And even if the line lengths are not known in advance, but (1) you're going to want to jump around a lot and (2) you can guaranteed that no one is messing with your file in the mean time you could make one pass to form a index, and use that thereafter.