boost :: archive :: binary_oarchive =程序崩溃?

时间:2012-03-04 17:20:39

标签: c++ windows serialization boost

使用boost::archive::binary_oarchive时遇到问题。执行程序时,我在实例化ia >> boost::serialization::make_binary_object(buffer, size)时遇到程序崩溃。 使用boost::archive::text_oarchive可行...

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/binary_object.hpp>
#include <iostream>
#include <fstream>
using namespace std;
void save()
{
    size_t size = 0;     
    std::ifstream infile("any_file.png", std::ios::in | std::ios::binary | std::ios::ate);
    if (infile.is_open())
    {
        size = infile.tellg();
        char *buffer = new char[size];
        infile.seekg(0, ios::beg);
        infile.read(buffer, size);
        infile.close();

        std::ofstream file("archiv.bin");
        boost::archive::binary_oarchive oa(file);
        oa << size;
        oa << boost::serialization::make_binary_object(buffer, size);
        file.close();

        delete [] buffer;
    }
}

void load()
{
    size_t size = 0;
    std::ifstream file("archiv.bin");
    boost::archive::binary_iarchive ia(file);

    ia >> size;
    char *buffer = new char[size];
    ia >> boost::serialization::make_binary_object(buffer, size);  //program crash
    file.close();

    ofstream outfile("any_file_out.png", ios::out | ios::binary); 
    for(size_t i = 0; i < size; i++)
    {
        outfile << buffer[i];
    }
    outfile.close();
    delete [] buffer;
}

int main()
{
    save();
    load();
    return 0;
}

提前谢谢!

编辑: 这是它的工作原理。

...
std::ofstream file("archiv.bin", ios_base::binary);
...
std::ifstream file("archiv.bin", ios_base::binary);
...

1 个答案:

答案 0 :(得分:1)

解决方案出现了:)

...
std::ofstream file("archiv.bin", ios_base::binary);
...
std::ifstream file("archiv.bin", ios_base::binary);
...

现在完美无缺!