首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JSONCPP追加到文件

JSONCPP追加到文件
EN

Stack Overflow用户
提问于 2019-03-05 03:27:50
回答 1查看 2.2K关注 0票数 0

我使用JSONCPP来记录我在服务器上收到的消息,但是它没有附加消息,而是替换了最后一条消息。这是我的代码: ofstream和event是私有成员。

代码语言:javascript
复制
  //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();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-05 04:45:35

您可以将该文件作为Json::Value对象加载,并将其附加到那里。注意:此代码片段要求json具有一个数组作为文件中的顶级项,例如:

messageLogs.json

代码语言:javascript
复制
[]

main.cpp

代码语言:javascript
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54990260

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档