我正在使用二进制序列化带有 boost 的类。我使用 ios::append 来继续将多个对象附加到该文件。如何检索所有存储的对象?
这是我的测试类,它尝试多次序列化并检索它们。我已经评论了我没有获得正确数据的故障点。
using namespace std;
class Data {
public:
double get_latitude() const {
return _latitude;
}
double get_longitude() const {
return _longitude;
}
void set_latitude(double _latitude) {
this->_latitude = _latitude;
}
void set_longitude(double _longitude) {
this->_longitude = _longitude;
}
private:
double _latitude;
double _longitude;
friend class boost::serialization::access;
// When the class Archive corresponds to an output archive, the
// & operator is defined similar to <<. Likewise, when the class Archive
// is a type of input archive the & operator is defined similar to >>.
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & _latitude;
ar & _longitude;
}
};
class DataTest: public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE( DataTest);
CPPUNIT_TEST(testMultipleSaveData);
CPPUNIT_TEST_SUITE_END();
public:
void testMultipleSaveData() {
Data data;
data.set_latitude(1.0);
data.set_longitude(2.0);
saveData(data);
Data secondData;
secondData.set_latitude(5.0);
secondData.set_longitude(6.0);
saveData(secondData);
Data returnData;
Data return2Data;
{
// create and open an archive for input
std::ifstream ifs("data.dat", ios::binary);
boost::archive::binary_iarchive ia(ifs);
// read class state from archive
ia >> returnData;
ia >> return2Data;
// archive and stream closed when destructors are called
}
CPPUNIT_ASSERT_EQUAL(data.get_latitude(), returnData.get_latitude());
CPPUNIT_ASSERT_EQUAL(data.get_longitude(), returnData.get_longitude());
//Failure on next line
CPPUNIT_ASSERT_EQUAL(secondData.get_latitude(), return2Data.get_latitude());
CPPUNIT_ASSERT_EQUAL(secondData.get_longitude(), return2Data.get_longitude());
}
void saveData(Data data) {
std::ofstream ofs("data.dat", ios::binary | ios::app);
boost::archive::binary_oarchive oa(ofs);
oa << data;
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( DataTest);
决定添加另一个答案以避免完全混乱。
你的问题是你序列化到单独的实例boost::archive::binary_oarchive
. 提升存档在文件的开头存储一些内部信息(我不会将其称为标头,因为增强序列化有单独的标头来存储版本号),并且您会收到此信息的两个副本,位于文件的开头和数据序列化之间。
提升存档不是为这种用途而设计的。甚至指定boost::archive::no_header
像:
boost::archive::text_oarchive oa(ofs, boost::archive::no_header);
没有帮助,因为此选项配置另一个包含版本号的标头。您需要序列化到同一个实例提升存档.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)