c++ - JsonCpp 写回 Json 文件

标签 c++ json jsoncpp

我有一个包含以下内容的配置文件:

{
    "ip": "127.0.0.1",
    "heartbeat": "1",
    "ssl": "False",
    "log_severity": "debug",
    "port":"9999"
}    

我已使用 JsonCpp 读取上述配置文件的内容。读取Config File内容正常,但是写入Config File内容失败。我有以下代码:

#include <json/json.h>
#include <json/writer.h>
#include <iostream>
#include <fstream>
int main()
{
    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    Json::StyledStreamWriter writer;
    std::ifstream test("C://SomeFolder//lpa.config");
    bool parsingSuccessful = reader.parse( test, root );
    if ( !parsingSuccessful )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << "Failed to parse configuration: "<< reader.getFormattedErrorMessages();
    }
    std::cout << root["heartbeat"] << std::endl;
    std::cout << root << std::endl;
    root["heartbeat"] = "60";
    std::ofstream test1("C://SomeFolder//lpa.config");
    writer.write(test1,root);
    std::cout << root << std::endl;
    return 0;
}

该代码在控制台中打印出正确的输出,但是当该代码执行时配置文件为空。如何使此代码工作?

最佳答案

您需要做的就是显式关闭输入流

test.close(); // ADD THIS LINE
std::ofstream test1("C://LogPointAgent//lpa.config");
writer.write(test1,root);
std::cout << root << std::endl;
return 0;

关于c++ - JsonCpp 写回 Json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27486538/

相关文章:

r - 如何从编码折线创建空间线数据框?

采用 json 对象的 Python 函数返回 mongodb 查询对象

c++ - 在 C++ 中读取 json 文件

c++ - 使用 C++ 和 jsoncpp 将文件行写入 JSON

c++ - Json::Value 返回时会发生变化吗?

c++ - 确定 64 位中最右边第 n 位集的快速方法

c++ - sprintf - 字符串前有 4 个无用的 ascii 字符

c++ - 为什么这个 std::bind 没有转换为 std::function?

c++ - 我怎样才能找到拷贝的来源?

json - 验证 Node 中 swagger json.schema 的 POST 数据