在下面的代码中,我通过boost序列化库在备份序列化文件中写入文件内容,但是我观察到每次我需要将所有数据存储在文件中时,我才能读取整个数据。 因此,如果我不执行写操作,只是尝试将存储数据存储在备份文件中,则无法读取存储在备份文件中的任何内容。 执行整个代码后,我能够从文件中读取序列化映射,但只执行读操作而不写无法读取任何内容。 下面是用于写入操作的注释代码片段。如果代码中有问题,请提出建议。
/*obj.writefile("wasim",23);
obj.writefile("available",12);
obj.writefile("jack",32);
obj.writefile("john",37);
obj.writefile("hate",11);
obj.writefile("kk",37);*/
obj.writefile("abc",39);
obj.readfile();
ret_value=obj.parse_map();
cout<<ret_value;
#include <map>
#include <sstream>
#include <string>
#include <boost/serialization/map.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <fstream>
#include <iostream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
using namespace std;
enum RESULT_T
{
ret_error =-1,
ret_success = 0
} ;
class object_model
{
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & mymap;
}
map<string,int> mymap;
public:
object_model(){
};
void writefile (string key,int value);
map<string, int> readfile();
RESULT_T parse_map();
int deserialize_validation();
};
RESULT_T object_model::parse_map()
{
auto new_map = readfile();
for (auto itr: new_map)
{
cout<<itr.first <<":"<<itr.second<<endl;
}
return ret_success;
}
void object_model::writefile( string key, int value)
{
mymap[key] = value;
std::ofstream ss("backup",ios::binary);
boost::archive::binary_oarchive oarch(ss);
oarch << mymap;
}
map<string, int> object_model::readfile()
{
std::map<string,int> new_map;
{
std::ifstream ifs("backup",ios::binary);
boost::archive::binary_iarchive ia(ifs);
ia >> new_map;
}
return new_map;
}
int main()
{
RESULT_T ret_value;
object_model obj;
obj.writefile("hate",11);
obj.writefile("wasim",23);
obj.writefile("available",12);
obj.writefile("jack",32);
obj.writefile("john",37);
obj.writefile("kk",37);
obj.readfile();
ret_value=obj.parse_map();
cout<<ret_value;
}