输出比多态文本存档更多的东西

时间:2014-12-11 12:09:47

标签: c++ c++11 boost

我正在使用Shark机器学习库,并使用boost::archive::polymorphic_text_(io)archive类将其分类器输出到文件。

我正在创建一个单词模型包,我还需要写入文件(使用我自己的代码),我还需要将其输出到文件。

我最好将它输出到与分类器相同的文件中。是否可以将事物写入与使用多态文本存档时相同的文件?只是在存档开始时传递fstream就足够了吗?

编辑:稍微清楚一点:Boost是否支持我将其他内容与这些档案一起放在文件中?

1 个答案:

答案 0 :(得分:2)

首先关闭: Streams Are Not Archives

我的第一反应是"你试过"。但是,我很感兴趣,并且在文档中找不到任何相关内容,所以我自己做了一些测试:

  • 答案似乎是"否",它不受支持
  • 它似乎适用于二进制档案
  • 它似乎崩溃了,因为xml / text存档在输入缓冲区中留下尾随0xa个字符。如果" next"这些不会造成问题。要读取的存档也是文本,但显然打破了二进制存档。

这是我的测试员:

<强> Live On Coliru

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>

int data = 42;

template <typename Ar>
void some_output(std::ostream& os)
{
    std::cout << "Writing archive at " << os.tellp() << "\n";
    Ar ar(os);
    ar << BOOST_SERIALIZATION_NVP(data);
}

template <typename Ar>
void roundtrip(std::istream& is)
{
    data = -1;
    std::cout << "Reading archive at " << is.tellg() << "\n";
    Ar ar(is);
    ar >> BOOST_SERIALIZATION_NVP(data);
    assert(data == 42);
}

#include <sstream>

int main()
{
    std::stringstream ss;

    //some_output<boost::archive::text_oarchive>(ss); // this derails the binary archive that follows
    some_output<boost::archive::binary_oarchive>(ss);
    some_output<boost::archive::xml_oarchive>(ss);
    some_output<boost::archive::text_oarchive>(ss);

    //roundtrip<boost::archive::text_iarchive>(ss);
    roundtrip<boost::archive::binary_iarchive>(ss);
    roundtrip<boost::archive::xml_iarchive>(ss);
    roundtrip<boost::archive::text_iarchive>(ss);

    // just to prove that there's remaining whitespace
    std::cout << "remaining: ";
    char ch;
    while (ss>>std::noskipws>>ch)
        std::cout << " " << std::showbase << std::hex << ((int)(ch));
    std::cout << "\n";

    // of course, anything else will fail:
    try {
        roundtrip<boost::archive::text_iarchive>(ss);
    } catch(boost::archive::archive_exception const& e)
    {
        std::cout << "Can't deserialize from a stream a EOF: " << e.what();
    }
}

打印:

Writing archive at 0
Writing archive at 44
Writing archive at 242
Reading archive at 0
Reading archive at 44
Reading archive at 240
remaining:  0xa
Reading archive at 0xffffffffffffffff
Can't deserialize from a stream a EOF: input stream error