我一直未能找到这个问题的直接答案。在搜索了一段时间之后,我编写了以下代码,但我确信有一种更简单的方法来完成相同的任务。
int persistJSONChanges(rapidjson::Document& fa_cloneDoc, string jsonFilePath)
{
FILE* lp_file = fopen(jsonFilePath.c_str(), "w");
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
fa_cloneDoc.Accept(writer);
string temp=buffer.GetString();
unique_ptr<char[]>l_writeBuffer(new char[temp.size()]);
rapidjson::FileWriteStream l_writeStream(lp_file, l_writeBuffer.get(), temp.size());
rapidjson::PrettyWriter<rapidjson::FileWriteStream> l_writer(l_writeStream);
bool l_returnStatus=fa_cloneDoc.Accept(l_writer);
if(l_returnStatus==false)
{
cout<<endl<<"file update failed"<<endl;
return -1;
}
fclose(lp_file);
return 0;
}发布于 2018-11-30 05:12:30
我想你滥用了FileWriteStream。它只需要一个任意大小的缓冲区。
你只需要:
FILE* fp = fopen(...);
char buffer[1024];
FileWriteStream fs(fp, buffer, sizeof(buffer));
PrettyWriter<FileWriteStream> writer(fs);
document.Accept(writer);
fclose(fp);发布于 2018-11-30 07:18:20
我试过以下对我有用的方法:
int persistJSONChanges(rapidjson::Document& fa_cloneDoc, string jsonFilePath)
{
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
bool l_returnStatus=fa_cloneDoc.Accept(writer);
if(l_returnStatus==false)
{
fprintf(stdout,"\n[%s::%d] JSON File update failed\n",__FILE__,__LINE__);
return -1;
}
string temp=buffer.GetString();
ofstream out(jsonFilePath.c_str(),std::ofstream::trunc);
out<<temp;
return 0;
}发布于 2021-06-05 14:24:28
我不用
rapidjson::Document这是我的工作:
namespace rpj = rapidjson;
FILE* fp_r = fopen("json.json", "w" );
char buf[BUF_SIZE];
rpj::FileWriteStream os(fp_r, buf, sizeof (buf));
rpj::PrettyWriter<rpj::FileWriteStream> writer(os);
writer.StartObject();
writer.String("hello");
writer.String("world");
writer.String("arr");
writer.StartArray();
writer.Int(33);
writer.Int(34);
writer.Int(36);
writer.EndArray();
writer.EndObject();
fclose(fp_r);https://stackoverflow.com/questions/53388845
复制相似问题