文字列を取得したら、それをファイルに書き込むのは簡単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もあります。