Lucas Mezalira
Lucas Mezalira

Reputation: 183

c++ ifstream object "reseting"

I have a function func1(ifstream& fin) that uses multiple calls for fin.getline() to read from the file. Now inside this func1 I also call another function func2(ifstream&) that has to access the same file func1 is accessing. I could simply call func2 as func2(fin).

Now suppose that func1 read the file until line 4, and then func2 is called and do its thing, reading the file until line 7. Now this is the problem: as soon as funct2 returns to func1, I would like to continue reading the file from where func1 left, that is, line 5, but it isn't possible because fin is now "pointing" to line 8 of the file.

I have already tried defining func2 as func2(const ifstream&) and func2(const ifstream*) or creating a copy of fin inside func1 and passing it to func2, but the compiler will not accept any of these options.

What should I do? Thanks.

Upvotes: 0

Views: 80

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129314

Typically, if you want to "go back", you use fstream::tellg() to tell you where you are at the moment, and fstream::seekg() to go back to that point.

The other option, which I typically prefer, is to only read lines once, and have a cache/store of lines that holds enough lines that you can go back and forth over the area you want. Assuming the file isn't absolutely enormous, holding all lines in a vector works fairly well. If the file is several gigabytes, that may not be an option (on embedded devices, even a few megabytes may be too much to hold all), in which case you need to use some method of "discrding" stuff that you no longer need.

Upvotes: 2

Related Questions