我正在使用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
的方式上做错了。
进行更多的调试,看起来在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);