JSONCPP附加文件
JSONCPP append to file
我正在使用JSONCPP来记录我在服务器上收到的消息,但是它没有附加消息,而是替换了最后一条消息。这是我拥有的代码:Ofstream和事件是私人成员。
//std::ofstream myfile;
m_file.open ("messageLogs.json");
//Json::Value event;
Json::Value array(Json::arrayValue);
array.append(Json::Value(1));
array.append(Json::Value(1));
m_event["messages"]["time"] = "19:22";
m_event["messages"]["message"] = msg;
//populate object with objects
Json::StyledWriter writer;
m_file << writer.write(m_event) << std::endl;
m_file.close();
您可以将文件加载为Json::Value
对象,然后在此附加。请注意,此代码段要求JSON具有数组作为文件中的顶级项目,例如:
Messagelogs.json
[]
main.cpp
#include <iostream>
#include <fstream>
#include <json/json.h>
int main(int argc, char* argv[])
{
std::fstream m_file;
m_file.open ("messageLogs.json", std::ios::in);
Json::Reader reader;
Json::Value json_obj;
if(!reader.parse(m_file, json_obj, true))
{
// json file must contain an array
std::cerr << "could not parse the json file" << std::endl;
return -1;
}
m_file.close();
Json::Value m_event;
m_event["messages"]["time"] = "19:22";
m_event["messages"]["message"] = "Some message";//msg;
// append to json object
json_obj.append(m_event);
std::cout << json_obj.toStyledString() << std::endl;
// write updated json object to file
m_file.open("messageLogs.json", std::ios::out);
m_file << json_obj.toStyledString() << std::endl;
m_file.close();
return 0;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 使用 jsoncpp 读取 JSON 文件
- 使用 JSONCPP 将 JSON 数据增量写入文件
- 转义 json 的文件路径 (JsonCPP)
- c++ jsoncpp 读取 json 文件
- 使用 jsonCpp 库从C++文件中解析 json 时出错
- JSONCPP附加文件
- 使用 C++ 和 Jsoncpp 解析 AWS S3 中的 json 文件
- 使用C++和jsoncpp将文件行写入JSON
- 将JSON文件中的单个值替换为JSONcpp