Go back one line on a text file C++
Asked Answered
S

2

10

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.

Scalar answered 6/12, 2014 at 11:38 Comment(1)
I would think std::istream::seekg in concert with the length of the line you just read could be somewhat helpful.Bosomy
S
18

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.

Scend answered 6/12, 2014 at 11:56 Comment(0)
L
2

The easiest thing by far, if you only ever want to roll back by one line, is always to keep track of the line you're on and the line before.

Maintain a cur variable that stores the current line, and prev that stores the previous one. When you move to the next line, you copy cur into prev, and read the new line into cur.

That way, you always have the previous line available.

Locke answered 6/12, 2014 at 11:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.