On Jul 24, 1:30 am, Peng Yu <PengYu...@gmail.comwrote:
Suppose, I have the following code and the requirement is
written along with the code. I'm wondering if there is a way
to restore the state of an istream.
int n, m;
std::ifstream file("file.txt");
file >n;
//I want to restore the state of 'file' here.
file >m;//so that m would get the same value as n.
It depends which state you're talking about. Although there's
no standard solution, it's usual to have a class which saves and
restores the formatting state (fmtflags, precision and fill).
There's also a function copyfmt() which copies everything but
the error status and the streambuf pointer; be careful with this
one, however, because it can change the exceptions mask, and
thus trigger an exception.
If you want to reread from the same place, istream::tellg() and
istream::seekg() are a possible solution (but be aware that they
don't work on all types of streams, and may not work on an
ifstream, depending on the file type). You can't, and normally
don't want to save and restore error state; if you're going back
in the file, after having (maybe) seen EOF, just use
ios::clear(). (If the first read succeeded, there was no error
before then.)
There is, IMHO, an error in the standard here. If eofbit is
set, but no other status bit, seekg() should logically clear it,
since the fact that you are at the end of file (but no operation
has actually failed yet) doesn't prevent you from seeking
(although it does mean that a read will fail), and after
seeking, you probably aren't at the end of file anymore. The
standard does allow seekg() to proceed if eofbit is set (unlike
the case with other functions), but doesn't have it resetting
this bit. As a general principle, I would suggest using clear()
before seeking.
Of course, if you really want to restore exactly the initial
state, the simplest solution is to just construct a new
instance.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34