以前用fopen函数打开过txt文件。json文件要怎么打开 .怎么与cJSON_Parse函数配合起来使用。。我是初学者
下面是一个示例代码,使用 fopen 函数打开一个名为 "data.json" 的 json 文件,然后使用 cJSON_Parse 函数解析 json 数据:
#include <stdio.h>
#include <cJSON.h>
int main() {
// 打开文件
FILE *fp = fopen("data.json", "r");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
// 读取文件内容
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
char *data = (char*)malloc(size + 1);
fread(data, 1, size, fp);
data[size] = '\0';
fclose(fp);
// 解析 json 数据
cJSON *json = cJSON_Parse(data);
if (json == NULL) {
printf("Error parsing json\n");
return 1;
}
// 在这里使用 json 数据
// ...
// 释放 json 内存
cJSON_Delete(json);
free(data);
return 0;
}
json文件也是简单的文本文件,和txt一样可以用fopen打开读写。