【问题标题】:Convert binary ostringstream to char array in google::dense_hash_map在 google::dense_hash_map 中将二进制字符串流转换为 char 数组
【发布时间】:2013-03-14 13:01:12
【问题描述】:

二进制 ostringstream 有问题。我想序列化谷歌的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.....

【问题讨论】:

  • 你的字符串流是二进制的,你想把它打印成字符串???
  • 我想将其转换为 char * 以便将其存储在 XML 文件中。
  • binary 标志对ostringstream 没有影响(并且out 标志是自动添加的。声明ostringstream 的常用方法就是std::ostringstream output;。
  • 好吧,顺其自然。如何将流的内容转换为 char 数组?我已经尝试了所有可能的功能和组合,直接从缓冲区读取,添加所有可用的标志,但到目前为止没有任何效果。
  • @PavloDyban 但您正在读取或写入二进制数据,不是吗?

标签: c++ serialization hash iostream


【解决方案1】:

在文档中搜索并尝试了一段时间后,我自己找到了答案。

要访问存储在流中的单独字符,应该使用流迭代器(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;
}

谢谢大家的cmets!

【讨论】:

    猜你喜欢
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2013-07-17
    相关资源
    最近更新 更多