c++ - 如何检测boost存档中是否还有任何东西

标签 c++ serialization boost

有没有一种方法可以检测在我读取 boost 存档后是否还有任何东西留在里面?我试过这段代码:

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
}

我希望流对象被更新,就好像我直接从它读取一样,但在上面的代码中,stream.eof() 总是 false,尽管我阅读了所有内容写。将字符串更改为 int 得到相同的结果。

我想要这种能力的原因是当我阅读的类型与我写的不同时:

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

我知道在这种情况下我无能为力,但我希望至少检查我是否阅读了所有内容会给我一些指示,表明读写之间是否存在不一致。有什么想法吗?

最佳答案

stream.eof() 可能会在您尝试读取文件末尾后的内容时设置,而不是在您从中读取最后一个字节时设置。

在流中启用异常并尝试读取直到抛出异常。

关于c++ - 如何检测boost存档中是否还有任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3598775/

相关文章:

php - 我在 115 的偏移 0 处出现反序列化错误

C++ boost log位置(索引)格式对齐

c++ - 在 lambda 函数中捕获 boost::asio::thread_pool

c++ - 编译 Boost.Asio 示例代码时出错

c++ - 如何从汇编代码中找出函数原型(prototype)?

c++ - 将 char[] 附加到具有特定长度的 std::string

c++ - 类外的类函数模板定义

c++ - QtCreator : symbol(s) not found for architecture x86_64 issue on Mac OS Mavericks

python - 在不反序列化的情况下操作 JSON

python - 如何从 Python 中的文件/流中懒惰地读取多个 JSON 值?