【问题标题】:How to detect whether there is anything left inside a boost archive如何检测升压档案中是否还有任何东西
【发布时间】:2010-08-30 08:02:49
【问题描述】:

有没有办法在我读取 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

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

【问题讨论】:

  • 试试:if (stream.peek(), !stream.eof())。在您尝试阅读某些内容之前,不会设置标志。
  • @GMan,我认为它应该作为答案发布:)

标签: c++ serialization boost


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在尝试某些操作之前,流无法设置任何标志。

    您可以使用peek() 查看并返回但不能删除流中的下一个字符。这足以设置一个标志,所以这样做:if (stream.peek(), !stream.eof()) /* peek was not eof */

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多