将二进制ostringstream转换为google :: dense_hash_map中的char数组

时间:2013-03-14 13:01:12

标签: c++ serialization hash iostream

我遇到了二进制 ostringstream的问题。我想序列化Google的dense_hash_map。这可以使用文件句柄,但不能使用ostringstream,即使是docs claim this must be possible

以下代码有效:

char *serializeTable( size_t &length ) {
    // serialize to a temp file
    FILE *f = fopen("D:\\Dumps\\Serialization2File.txt", "w");
    bool result1 = serialize<Serializer, FILE>(m_serializer, f);
    std::cout << "result1 = " << result1 << std::endl;

    fseek(f, 0, SEEK_END);
    int mylen = ftell(f);
    fclose(f);

    // read binary data from file
    char *readbuf = new char[mylen];
    std::ifstream rf("D:\\Dumps\\Serialization2File.txt", std::ios_base::binary);
    rf.read(readbuf, mylen);
    rf.close();

    std::ofstream check("D:\\Dumps\\CheckSerializer.txt", std::ios_base::binary);
    check.write(readbuf, mylen);
    check.close();

    length = mylen;
    return readbuf;
}

以下代码仅打印前4个符号。数组的其余部分由'\0' s:

组成
char *serializeTable( size_t &length ) {
    std::ostringstream output("", std::stringstream::out | std::stringstream::binary);
    bool result = serialize<Serializer, std::ostringstream>(m_serializer, &output);
    auto str = output.str();
    std::cout << "str = " << str << std::endl;
}

输出:

str = W�B

而不是:

E1eGQgAAAAAAAgAAAAAAAAAAksFLAAAAAAAAAAAAAAAAAGWwQAUAAAAAAAAAAAAAAAAAakANCg.....

1 个答案:

答案 0 :(得分:0)

经过一段时间搜索文档并四处寻找,我自己找到了答案。

要访问存储在流中的单独字符,应使用流迭代器(http://www.dyn-lab.com/articles/c-streams.html,第6部分)。

我的代码现在看起来如下:

char *serializeTable( size_t &length ) {

    std::stringstream stream("", std::stringstream::out | std::stringstream::in | std::stringstream::binary);
    //std::ostringstream output("", std::stringstream::binary);


    bool result = serialize<Serializer, std::stringstream>(m_serializer, &stream);
    std::istreambuf_iterator<char> itt(stream.rdbuf()), eos;
    std::vector<char> serialVector;
    serialVector.reserve(619999); // just a guess
    while(itt != eos) {
        char c = *itt++;
        serialVector.push_back(c);
    }

    length = serialVector.size();

    char *serial = new char[length];
    int index = 0;
    for each(char a in serialVector) {
        serial[index++] = a;
    }
    return serial;
}

感谢大家的评论!