Serialize multiple objects

I am trying to create a persistence module, and Im thinking about serializing / deserializing the class I need to persist in the file. Is it possible with Boost serialization to write multiple objects to the same file? How can I read or scroll through entries in a file? Google protocol buffers might be better for me if good performance is a condition?

+4
source share
2 answers

A serialization library will not be very useful if it cannot serialize multiple objects. You can find answers to all questions if you read very extensive documentation .

+4
source

I am involved in training, and I think you can use boost serialization as a log file and continue to add values โ€‹โ€‹using your own logic. I ran into the same problem, and if I'm not mistaken, your code will be something like this:

#include <iostream> #include <fstream> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> int main() { int two=2; for(int i=0;i<10;i++) { std::ofstream ofs("table.txt"); boost::archive::text_oarchive om(ofs); om << two; two = two+30; std::cout<<"\n"<<two; } return 0; } 

Here, when you close the curly braces (loop brackets), the serialization file closes. And you can see only one value written in the table.txt file, if you want to save several values, your code should look something like this:

 #include <iostream> #include <fstream> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> int main() { int two=2; { std::ofstream ofs("table.txt"); boost::archive::text_oarchive om(ofs); for(int i=0;i<10;i++) { om << two; two = two+30; std::cout<<"\n"<<two; } } return 0; } 

Here you can see that the brackets containing boost :: serialization :: text_oarchive only close when I have finished serializing the result of my logic.

0
source

All Articles