Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go back one line on a text file C++

Tags:

c++

file

getline

my program reads a line from a text file using :

std::ifstream myReadFile("route.txt");
getline(myReadFile, line)

And if it finds something that i'm looking for (tag) it stores that line in a temp String. I wan't to continue this until i find some other tag, if i find an other tag i want to be able to return to the previous line in order for the program to read if again as some that other tag and do something else.

I have been looking at putback() and unget() i'm confuse on how to use them and if they might be the correct answer.

like image 491
IzonFreak Avatar asked Dec 06 '14 11:12

IzonFreak


1 Answers

Best would be to consider a one pass algorithm, that stores in memory what it could need at the first tag without going back.

If this is not possible, you can "bookmark" the stream position and retreive it later with tellg() and seekg():

streampos oldpos = myReadFile.tellg();  // stores the position
....
myReadFile.seekg (oldpos);   // get back to the position

If you read recursively embedded tags (html for example), you could even use a stack<streampos> to push and pop the positions while reading. However, be aware that performance is slowed down by such forward/backward accesses.

You mention putback() and unget(), but these are limited to one char, and seem not suited to your getline() approach.

like image 185
Christophe Avatar answered Sep 19 '22 14:09

Christophe