4

Im trying to build a persistence module and Im thinking in serialize/deserialize the class that I need 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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I read it, but if you see the documentation, all the examples are making only one writing to the same file, and later they read this entry. But there is no example about looping through objects in the same file, or getting object serialized in file at position X. Could it be?
There is usually no need to loop yourself since the library can serialize both arrays and standard containers. And I don't think you can read the file from random location, serialization libraries work sequentially, you write all your objects in order and then you read them back in the same order.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.