views:

41

answers:

2

Is there a way to detect whether there is anything left inside a boost archive after I read from it? I tried this piece of code:

const string s1("some text");
std::stringstream stream;
boost::archive::polymorphic_text_oarchive oAr(stream);
oAr << s1;

boost::archive::polymorphic_text_iarchive iAr(stream);
string s2;
iAr >> s2;

if (!stream.eof())
{
    // There is still something inside the archive
}

I expected stream object to be updated as if I read directly from it, but in the above code stream.eof() is always false although I read everything I had written. Changing string to int gave the same result.

The reason I wanted this ability is for situations when I read not the same types I write:

const string s1("some text");
std::stringstream stream;
boost::archive::polymorphic_text_oarchive oAr(stream);
oAr << s1;

boost::archive::polymorphic_text_iarchive iAr(stream);
int s2;
iAr >> s2; // string was written but int is read

I know that there isn't much I can do in this situation, but I hoped that at least checking that I read everything will give me some indication whether there was some inconsistency between reads and writes. Any ideas?

+1  A: 

stream.eof() may be set when you tried to read something after end of file, not when you have read last byte from it.

Enabling exceptions in stream and trying to read until exception thrown may work.

blaze
+2  A: 

A stream can't set any flags until it's tried some operation.

You can use peek() to peek at and return, but not remove, the next character in a stream. This is enough to set a flag, so do: if (stream.peek(), !stream.eof()) /* peek was not eof */.

GMan