欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

boost 序列化 博客分类: c++boost boost序列化 

程序员文章站 2024-03-06 13:38:20
...
在用boost 二进制序列化类的时候,需要注意动态调用文件打开标志std::ios::binary:


The flag std::ios::binary is required only in Windows, where the default mode (ascii) would translate \n\r to \n (and vice versa), thus corrupting any data that is not textual.

#include <boost/serialization/string.hpp>
#include "boost/archive/binary_oarchive.hpp"
#include "boost/archive/binary_iarchive.hpp"
#include "boost/iostreams/stream.hpp"
#include <boost/serialization/version.hpp>

typedef struct tagWorkStruct
{
	string groundTruthFile;
	string jpegFile;
	int workId;
}WorkStruct;

template<class Archive>
void serialize(Archive &ar, AddNewCardWorkStruct &g, const unsigned int version)
{
	ar & g.groundTruthFile;
	ar & g.jpegFile;
	ar & g.workId;
}


//写入文件
string fileName = "test.dat";
ofstream os(fileName.c_str(), std::ios::binary);
if (!os.fail())
{
    try
    {
        WorkStruct tempStruct;
        boost::archive::binary_oarchive oa(os);
        oa << tempSturct;
    }
    catch(...) 
    {
    }
}


//读取文件
ifstream is(dataFileName.c_str(), std::ios::binary);
if (!is.fail())
{
   try
   {
	WorkStruct tempStruct;
	boost::archive::binary_iarchive ia(is);
	ia >> tempStruct;
   }
   catch (...)//boost::archive::archive_exception
   {
   }
}
相关标签: boost 序列化