Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With an std::ifstream, is there a difference between ignoring characters and seeking?

All the documentation I can find says that std::basic_istream<>::ignore(n) "extracts and discards characters", but it's not terribly clear on what this extraction means.

For an std::ifstream in particular, could an implementation make it equivalent to simply seekg-ing in the file? If so, do mainstream implementations do that?

Otherwise, if characters really are "read" before being thrown away, it seems like ignore is a poor choice when seekg is available (e.g. with a file or string stream).

like image 854
Lightness Races in Orbit Avatar asked Jul 06 '15 12:07

Lightness Races in Orbit


1 Answers

Yes, there's a difference.

Even if we merely considered the as-if rule, extracting characters has an effect on the stream state (consider the various state flags), and we can see from the libstdc++ implementation that the stream behaves as if the extracted characters were used by the caller.

If there were any "optimisation" for skipping over the characters entirely then this observable behaviour would be different.

To apply this "optimisation" you should perform the seekg yourself, being careful not to seek past the end of the stream.

like image 69
Lightness Races in Orbit Avatar answered Sep 28 '22 07:09

Lightness Races in Orbit