Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 727
Jim Avatar asked Mar 05 '11 23:03

Jim


People also ask

How do you go to a specific line in a file in C?

If you know the length of each line, you can use fseek to skip to the line you want. Otherwise, you need to go through all lines. Show activity on this post. buffer =(char*)malloc(sizeof(char) * strlen(line));

How do you jump to a line in C++?

The \n Character The other way to break a line in C++ is to use the newline character — that ' \n ' mentioned earlier. This is line one. This is line two. This is line one.


1 Answers

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

like image 79
Xeo Avatar answered Oct 04 '22 17:10

Xeo