|
Boost Users : |
Subject: Re: [Boost-users] [serialization] how can load the nth element usingbinary_archive?
From: Robert Ramey (ramey_at_[hidden])
Date: 2011-10-23 12:24:35
gongyiling wrote:
> 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 obj[i]'s
> 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;
> ofs.close();
>
> 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!
I can't see a way to do this without making non-trivial changes
in the serialization library
Robert Ramey
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net