1

我正在使用https://github.com/nlohmann/json库将我的对象写入 BSON。我已经json通过将文件写入 json 以供审查来验证创建实例,因此该部分代码按预期工作。不过,一旦我换回 bson,我就会遇到问题。

这是我正在使用的代码片段:

//I have written out json_triangle_container to verify it looks correct
//so I am sure the problem is not here
json json_instance = <my function to create this instance>
std::vector<std::uint8_t> v_bson = json::to_bson(json_instance);

//writing the vector out here
auto bsonFilename = std::string("json_instance.bson");
std::ofstream bsonfile(bsonFilename, std::ios::out | std::ios::binary);
bsonfile.write((char*)&v_bson[0], v_bson.size() * sizeof(v_bson[0]));
bsonfile.close();

//reading it back in here
std::ifstream r_file(bsonFilename, std::ios::in | std::ios::binary | std::ios::ate);
std::streampos size = r_file.tellg();
r_file.seekg(0, std::ios::beg);
char* memblock = new char[size];
r_file.read(memblock, size);
r_file.close();

//printing out the json object for testing
auto json_instance_read = json::from_bson(memblock); //this is where it is blowing up
std::cout << json_instance_read << std::endl; 

我得到一个例外,上面写着:

Exception thrown at 0x00007FFF4EE6A839 in test.exe: Microsoft C++ exception: nlohmann::detail::parse_error at memory location 0x0000006AB4D5F470.

json::from_bson(v_bson )如果我称它为解析良好,那也值得注意。我验证了正在读取的数组大小与我写出的向量大小相同。bson所以这让我相信我在最初写出来的时候做错了什么。


编辑
使用一些在线工具将我生成的 bson 文件转换为 json 似乎写作是正确的。所以这表明我的读取功能是问题所在。

再做一些调试,看起来v_bson vector第 3 项中的值'\0'我认为会让读者失望,并且在阅读整个文件之前就停止了。我通过检查的大小确认了这一点memblock,它只有 3 个字符长。

所以问题发生了一点变化:
我如何告诉ifstream读者忽略它似乎认为是 EOF 字符的内容?

我发现的所有内容都说要确保用 初始化它std::ios::binary,我这样做:

std::ifstream r_file(bsonFilename, std::ios::in | std::ios::binary | std::ios::ate);
4

0 回答 0