用c++写一个读入json文件的示例程序
时间: 2023-04-12 12:01:45 浏览: 117
当然可以,以下是一个简单的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "cJSON.h"
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <json_file>\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (!fp) {
printf("Failed to open file: %s, error: %s\n", argv[1], strerror(errno));
return 1;
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *json_str = (char *)malloc(size + 1);
if (!json_str) {
printf("Failed to allocate memory\n");
fclose(fp);
return 1;
}
fread(json_str, 1, size, fp);
fclose(fp);
cJSON *root = cJSON_Parse(json_str);
if (!root) {
printf("Failed to parse json string\n");
free(json_str);
return 1;
}
cJSON *name = cJSON_GetObjectItem(root, "name");
if (name) {
printf("name: %s\n", name->valuestring);
}
cJSON *age = cJSON_GetObjectItem(root, "age");
if (age) {
printf("age: %d\n", age->valueint);
}
cJSON_Delete(root);
free(json_str);
return 0;
}
```
这个程序使用了
阅读全文