c++ Json库读取和写入json文件

本文介绍了一个C++函数ModifyJsonConfigFileByPath,该函数通过Json库打开并修改json配置文件。它读取指定路径的config.json文件,更新其中的数据路径、模型路径、许可文件夹、验证配置和保存文件夹等字段,并将修改后的内容写回文件。
摘要由CSDN通过智能技术生成
#include "json\include\writer.h"
#include "json\include\reader.h"
#include <fstream>

bool ModifyJsonConfigFileByPath(const std::string &path)
{
Json::Reader reader;
Json::Value root;
std::string file = path + "/config/config.json";
std::ifstream in(file,std::ios_base::binary); //以二进制方式读进
if (!in)
{
return false;
}

bool bret = reader.parse(in, root);
if (!bret || root.isNull())
{
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C标准不直接支持读取写入JSON文件的功能,但可以使用第三方来实现。 以下是一些常用的C语言JSON: 1. cJSON:一个轻量级的JSON解析和生成。可以在GitHub上下载。 2. Jansson:一个C语言的JSON,支持解析和生成JSON数据。可以在GitHub上下载。 3. YAJL:一个快速的JSON解析器/生成器,支持流式处理JSON数据。可以在GitHub上下载。 使用这些可以方便地读取写入JSON文件。例如,使用cJSON可以通过以下方式读取JSON文件: ``` #include <stdio.h> #include <cJSON.h> int main() { FILE *file = fopen("data.json", "r"); if (file) { fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); char *buffer = (char*)malloc(size + 1); fread(buffer, 1, size, file); fclose(file); buffer[size] = '\0'; cJSON *json = cJSON_Parse(buffer); free(buffer); if (json) { // 处理JSON数据 cJSON_Delete(json); } else { printf("Error: Failed to parse JSON file."); } } else { printf("Error: Failed to open JSON file."); } return 0; } ``` 使用cJSON可以通过以下方式将JSON数据写入文件: ``` #include <stdio.h> #include <cJSON.h> int main() { cJSON *json = cJSON_CreateObject(); cJSON_AddStringToObject(json, "name", "John"); cJSON_AddNumberToObject(json, "age", 30); char *jsonString = cJSON_Print(json); cJSON_Delete(json); FILE *file = fopen("output.json", "w"); if (file) { fputs(jsonString, file); fclose(file); } else { printf("Error: Failed to open output file."); } free(jsonString); return 0; } ``` 这些代码示例可以帮助您开始使用JSON读取写入JSON文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值