MarkB
MarkB

Reputation: 892

Data-Dependent Failure When Serializing std::vector to Boost Binary Archive

Just starting to familiarize myself with the Boost serialization library. I'm stumped on what appears to be a data-dependent failure:

The following code fails with input stream error

#include <cassert>
#include <vector>
#include <iostream>
#include <algorithm>
#include "boost/serialization/vector.hpp"
#include "boost/archive/text_iarchive.hpp"
#include "boost/archive/text_oarchive.hpp"
#include "boost/archive/binary_iarchive.hpp"
#include "boost/archive/binary_oarchive.hpp"

int main (void) {

    std::vector<int> v1(100);
    std::generate(v1.begin(), v1.end(), &std::rand);

    {
        std::ofstream ofs("test.out");
        boost::archive::binary_oarchive oa(ofs);
        oa << v1;
    }

    {
        std::vector<int> v2;
        std::ifstream ifs("test.out");
        boost::archive::binary_iarchive ia(ifs);
        ia >> v2;
        assert(v1 == v2);
    }

    return 0;
}

If I use boost::archive::text_[i/o]archive, the code passes.

If I comment out the std::generate line (still using binary_[i/o]archive), the code passes.

On the surface, this is almost impossible to believe. More likely, I am missing something obvious.

Lastly, using 1.53.

Upvotes: 2

Views: 484

Answers (1)

rhashimoto
rhashimoto

Reputation: 15869

It's possible that your fstream is converting 0x0a bytes that appear in your binary stream to your system line ending sequence which is not 0x0a. Try opening your files with the std::ios::binary mode, e.g.

    std::ofstream ofs("test.out", std::ios::out | std::ios::binary);

and

    std::ifstream ifs("test.out", std::ios::in | std::ios::binary);

Upvotes: 3

Related Questions