boost binary 序列化

在用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. 

C++代码   收藏代码
  1. #include <boost/serialization/string.hpp>  
  2. #include "boost/archive/binary_oarchive.hpp"  
  3. #include "boost/archive/binary_iarchive.hpp"  
  4. #include "boost/iostreams/stream.hpp"  
  5. #include <boost/serialization/version.hpp>  
  6.   
  7. typedef struct tagWorkStruct  
  8. {  
  9.     string groundTruthFile;  
  10.     string jpegFile;  
  11.     int workId;  
  12. }WorkStruct;  
  13.   
  14. template<class Archive>  
  15. void serialize(Archive &ar, AddNewCardWorkStruct &g, const unsigned int version)  
  16. {  
  17.     ar & g.groundTruthFile;  
  18.     ar & g.jpegFile;  
  19.     ar & g.workId;  
  20. }  
  21.   
  22.   
  23. //写入文件  
  24. string fileName = "test.dat";  
  25. ofstream os(fileName.c_str(), std::ios::binary);  
  26. if (!os.fail())  
  27. {  
  28.     try  
  29.     {  
  30.         WorkStruct tempStruct;  
  31.         boost::archive::binary_oarchive oa(os);  
  32.         oa << tempSturct;  
  33.     }  
  34.     catch(...)   
  35.     {  
  36.     }  
  37. }  
  38.   
  39.   
  40. //读取文件  
  41. ifstream is(dataFileName.c_str(), std::ios::binary);  
  42. if (!is.fail())  
  43. {  
  44.    try  
  45.    {  
  46.     WorkStruct tempStruct;  
  47.     boost::archive::binary_iarchive ia(is);  
  48.     ia >> tempStruct;  
  49.    }  
  50.    catch (...)//boost::archive::archive_exception  
  51.    {  
  52.    }  
  53. }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值