#define JSON_DIR "/home/zozo/test/"
void read_json_file()
{
FILE *fp = NULL;
cJSON *json;
char *out;
char *buf;
char filterfile_str[] = "jsonfile";
char json_str[] = "json";
char *namep = NULL, *typep = NULL; // namep:文件名 typep:文件类型
DIR *dp;
struct dirent *filename;
char file_path[200] = {0};
dp = opendir(JSON_DIR);
if (!dp)
{
fprintf(stderr, "open directory error\n");
return;
}
while (filename = readdir(dp))
{
// 筛选出以jsonfile开头的json格式文件
namep = strstr(filename->d_name, filterfile_str);
if (namep == NULL)
{
continue;
}
typep = strstr(filename->d_name, json_str);
if (typep == NULL) // 不是json文件
{
namep = NULL;
continue;
}
if (namep == filename->d_name) // 判断文件名以jsonfile开头
{
printf("filename:%-10s\td_info:%ld\t",
filename->d_name, filename->d_ino); // 打印出文件名
strcpy(file_path, JSON_DIR);
strcat(file_path, filename->d_name);
printf("file_path:%s\n", file_path);
if (NULL != (fp = fopen(file_path, "rb"))) // 打开文件
{
fseek(fp, 0, SEEK_END);
long len = ftell(fp); // 文件长度
fseek(fp, 0, SEEK_SET);
if (len < 0)
{
printf("invalid path\n");
}
// 根据文件大小申请内存空间, 多申请1个字节存放'\0'
buf = (char *)malloc(len + 1);
if (buf == NULL)
{
printf("No enough memory.");
exit(0);
}
// 读取文件内容至buf
int nread = fread(buf, len, 1, fp);
if (!nread)
{
printf("Failed to read the config file.");
}
// 关闭文件
fclose(fp);
// 字符串结尾
buf[len] = '\0'; // end of string*/
printf("len:%d\n", len);
json = cJSON_Parse(buf); // 解析json结构
if (json == NULL)
{
free(buf);
printf("Failed to parse the json file\n");
continue;
}
free(buf);
out = cJSON_Print(json);
printf("read json:%s\n", out); // 打印解析的json结构
// 进行后续处理
}
}
}
closedir(dp);
}