If I open a text file using fstream is there a simple way to jump to a specific line, such as line 8?
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));
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With