【发布时间】: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