Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

fstream - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(),'
');
    }
    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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...