开发者

Boost serialization multiple objects

开发者 https://www.devze.com 2023-01-19 01:47 出处:网络
Im trying to build a persistence module and Im thinking in serialize/deserialize the class that I ne开发者_JS百科ed to make persistence to a file. Is possible with Boost serialization to write multipl

Im trying to build a persistence module and Im thinking in serialize/deserialize the class that I ne开发者_JS百科ed to make persistence to a file. Is possible with Boost serialization to write multiple objects into the same file? how can I read or loop through entrys in the file? Google protocol buffers could be better for me if a good performance is a condition?


A Serialization library wouldn't be very useful if it couldn't serialize multiple objects. You can find all the answers if you read their very extensive documentation.


I am learning boost, and I think you can use boost serialization as a log file and keep adding values using your logic. I faced the same problem, and if I'm not wrong your code was 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 braces (braces of the loop), the serialization file closes. And you may see only one value written in table.txt , if you want to store multiple values, your code should 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;

    {
        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 braces enclosing boost::serialization::text_oarchive closes only when I'm done with serialization of the result of my logic.

0

精彩评论

暂无评论...
验证码 换一张
取 消