gpt4 book ai didi

c++ - 使用 Rapidjson 写入文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:33 24 4
gpt4 key购买 nike

如何使用 rapidjson 文档将一些数据写入文件:

这是我需要写的:

"Big Node ": [   
{ "Big Key": "Key Value 1", "Child Key": "Key Value 1", "Values": [ 1, 3, 4, 1, 2, 3 ] },
{ "Big Key": "Key Value 2", "Child Key": "Key Value 2", "Values": [ 17, 18, 5, 4, 17] }
]

最佳答案

获得字符串后,将其写入文件就像std::ofstream (path) << string 一样简单。 .

这是一个将 JSON 写入文件的示例:

char cbuf[1024]; rapidjson::MemoryPoolAllocator<> allocator (cbuf, sizeof cbuf);
rapidjson::Document meta (&allocator, 256);
meta.SetObject();
meta.AddMember ("foo", 123, allocator);

typedef rapidjson::GenericStringBuffer<rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<>> StringBuffer;
StringBuffer buf (&allocator);
rapidjson::Writer<StringBuffer> writer (buf, &allocator);
meta.Accept (writer);
std::string json (buf.GetString(), buf.GetSize());

std::ofstream of ("/tmp/example.json");
of << json;
if (!of.good()) throw std::runtime_error ("Can't write the JSON string to the file!");

如果你想避免双缓冲那么你可以直接写入ofstream :

struct Stream {
std::ofstream of {"/tmp/example.json"};
typedef char Ch;
void Put (Ch ch) {of.put (ch);}
void Flush() {}
} stream;

rapidjson::Writer<Stream> writer (stream, &allocator);
meta.Accept (writer);

还有 FileWriteStream .

关于c++ - 使用 Rapidjson 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21553512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com