从Boost序列化文件读取会引发异常

时间:2019-02-01 06:36:27

标签: c++ boost

我是C ++编码的新手。 我试图在Visual Studio上运行此代码以从boost序列化二进制文件读取,并且当我尝试从中读取二进制代码时,它将引发异常。

#include <iostream>
#include <fstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>


using boost::serialization::make_binary_object;

enum class Example : uint32_t {
    A = 1,
    B = 2,
};

int main() {
    int data = 5;

    std::ofstream f("data.dat", std::ios::binary);
    boost::archive::binary_oarchive ar(f);
    ar << make_binary_object(&data, sizeof(data));

    uint32_t restored_info;
    std::ifstream Obj_ifstream("data.dat", std::ios::binary);
    boost::archive::binary_iarchive ip_archive(Obj_ifstream);
    ip_archive >> restored_info;

    std::cout << "Testing " << std::endl;
    system("PAUSE");
}

例外:

  

terminate引发实例后调用   'boost :: archive :: archive_exception'
  what():输入流错误

1 个答案:

答案 0 :(得分:2)

您可以在关闭输出文件流之前打开输入文件流(无法同时打开文件以进行读取和写入)。确保先关闭它,如@ rafix07在其评论中所述,或像这样封装代码块:

#include <iostream>
#include <fstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>


using boost::serialization::make_binary_object;

enum class Example : uint32_t {
    A = 1,
    B = 2,
};

int main() {
    int data = 5;

    {
        std::ofstream f("data.dat", std::ios::binary);
        boost::archive::binary_oarchive ar(f);
        ar << make_binary_object(&data, sizeof(data));
    }
    {
        uint32_t restored_info;
        std::ifstream Obj_ifstream("data.dat", std::ios::binary);
        boost::archive::binary_iarchive ip_archive(Obj_ifstream);
        ip_archive >> restored_info;
        std::cout << "restored ino " << restored_info << std::endl;
    }

    std::cout << "Testing " << std::endl;
    system("PAUSE");
}