读取/写入BSON文件

时间:2020-01-08 20:35:07

标签: c++ bson nlohmann-json

我正在使用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);

0 个答案:

没有答案
相关问题