xy629
2023-02-22 05:48:05 +08:00
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <stdexcept>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
struct MyStruct
{
int i;
double d;
std::string s;
// 序列化成文本格式
template <class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & i;
ar & d;
ar & s;
}
};
int main()
{
// 将结构体序列化为二进制格式并写入文件
{
MyStruct s{42, 3.14, "hello world"};
std::ofstream ofs("data.bin", std::ios::binary);
boost::archive::binary_oarchive oa(ofs);
oa << s;
}
// 从文件中读取二进制数据并反序列化为结构体
{
MyStruct s;
std::ifstream ifs("data.bin", std::ios::binary);
boost::archive::binary_iarchive ia(ifs);
ia >> s;
// 验证反序列化结果是否正确
if (s.i != 42 || s.d != 3.14 || s.s != "hello world")
{
throw std::runtime_error("Deserialization failed");
}
}
return 0;
}