C語言中使用json文件存儲數據十分方便,可以通過json-c庫來實現。首先需要安裝json-c庫:
sudo apt-get install libjson-c-dev
接著,可以先創建一個json文件并寫入一些數據:
{
"name": "張三",
"age": 18,
"gender": "男",
"hobby": [
"唱歌",
"跳舞",
"健身"
]
}
接下來就可以在C程序中讀取和寫入這個json文件了:
#include <json-c/json.h>
#include <stdio.h>
int main() {
FILE *fp = fopen("example.json", "r");
if (fp == NULL) {
printf("打開文件失敗!\n");
return 1;
}
// 解析json文件
char buffer[1024];
fseek(fp, 0, SEEK_SET);
int count = fread(buffer, 1, sizeof(buffer), fp);
struct json_object *root = json_tokener_parse(buffer);
if (root == NULL) {
printf("解析json文件失敗!\n");
return 1;
}
// 獲取數據
struct json_object *name_object = NULL;
json_object_object_get_ex(root, "name", &name_object);
const char *name = json_object_get_string(name_object);
printf("name=%s\n", name);
// 更新數據
struct json_object *age_object = NULL;
json_object_object_get_ex(root, "age", &age_object);
int age = json_object_get_int(age_object);
age++;
json_object_set_int(age_object, age);
// 寫入文件
fseek(fp, 0, SEEK_SET);
fprintf(fp, "%s", json_object_to_json_string(root));
fclose(fp);
return 0;
}
這個程序首先在example.json中讀取數據,然后更新age字段并寫回文件中。