C言語:フォルダから必要なjsonファイルを抽出し、その内容を読み込む
2781 ワード
#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
");
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
", 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
");
}
// , 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
", len);
json = cJSON_Parse(buf); // json
if (json == NULL)
{
free(buf);
printf("Failed to parse the json file
");
continue;
}
free(buf);
out = cJSON_Print(json);
printf("read json:%s
", out); // json
//
}
}
}
closedir(dp);
}