2

I hope to serialize large size vector with cereal, C++ serialization library.

But, if trying to do that, the exception "Failed to read " + std::to_string(size) + " bytes from input stream! Read " + std::to_string(readSize)" is thrown.

Does anyone know a good solution for this? I'm using VisualStudio 2017.

The source code is shown below.

#include <iostream>
#include <fstream>
#include "include\cereal\cereal.hpp"
#include "include\cereal\archives\binary.hpp"
#include "include\cereal\types\vector.hpp"
#include "include\cereal\types\string.hpp"

void show(std::vector<int> v) {
    for (auto i : v)std::cout << i << ",";
    std::cout << std::endl;
}

int main(void) {

    const std::string file_name = "out.cereal";

    {
        std::vector<int> src;
        // const int STOP = 10;  //OK
        const int STOP = 1000; // NG

        for (int i = 0; i < STOP; i++)src.push_back(i);
        std::cout << "src:" << std::endl;
        show(src);

        std::ofstream ofs(file_name, std::ios::binary);
        cereal::BinaryOutputArchive archive(ofs);
        archive(src);
    }

    {
        std::vector<int> dst;
        std::fstream fs(file_name);
        cereal::BinaryInputArchive iarchive(fs);
        iarchive(dst);
        std::cout << "dst:" << std::endl;
        show(dst);
    }

#ifdef _MSC_VER
    system("pause");
#endif
    return 0;
}
4

1 回答 1

3

你的代码在 Linux 中对我来说很好,所以我认为这与 Windows 上的文本和二进制处理之间的区别有关。std::ios::binary在构建输入流时检查是否通过。也将其构造为std::ifstream而不仅仅是std::fstream.

我认为这可能与 Windows 期望(或添加)Unicode 字节顺序标记有关,这会使序列化程序感到困惑。

于 2017-12-12T21:38:58.670 回答