Boost logo

Boost Users :

Subject: [Boost-users] [serialization] how can load the nth element using binary_archive?
From: gongyiling (gongyiling2010_at_[hidden])
Date: 2011-10-23 10:05:32

Hello, Everyone:

    boost::serialization is a cool library. I use it in my project. I
encounter a problem now.
I serialized a array of objects to file as following:

    std::ofstream ofs(filename, std::ios_base::binary);
    boost::binary_oarchive oar(ofs);
    oar << obj[0] << obj[1] << ... << obj[n-1];

Now I want to load the obj[i] (i>=0 && i<n) from file. I tried recording
position in file, then set file stream's pointer to that position and trying
to load it, but
failed with exception input_stream_error, can I by any means doing that?

here is my minimun code segments:

struct word_block
    std::string word;
    template<typename Archive>
    void serialize(Archive & ar, const unsigned int file_version )
        ar & word;

int main(int argc, char* argv[])
    const char* filename = "words.idx";
    word_block wb1, wb2, wb2_r;

    std::ofstream ofs(filename, std::ios_base::binary);
    boost::archive::binary_oarchive oar(ofs);
    oar << wb1;
    size_t wb2_pos = ofs.tellp(); //record the position of wb2.
    oar << wb2;

    std::ifstream ifs(filename, std::ios_base::binary);
    boost::archive::binary_iarchive iar(ifs);
    ifs.seekg(wb2_pos); //set file pointer to wb2.
    iar >> wb2_r; //failed with exception input_stream_error.
    return 0;

Any idea is appreciated!

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at