JsonCpp写回Json文件

Pan*_*ant 5 c++ json jsoncpp

我有一个Config文件,其中包含以下内容:

{
    "ip": "127.0.0.1",
    "heartbeat": "1",
    "ssl": "False",
    "log_severity": "debug",
    "port":"9999"
}    
Run Code Online (Sandbox Code Playgroud)

我用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;
}
Run Code Online (Sandbox Code Playgroud)

代码在控制台中输出正确的输出,但是当执行此代码时,Config File为空.如何使此代码有效?

Shm*_*Cat 5

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

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