C语言:在文件夹中提取需要的json文件并读取其内容

#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);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值