C Readdir没有读取所有文件

时间:2016-12-04 19:21:09

标签: c linux file directory

我试图读取并处理目录中的所有文件。

如果只使用readdir()并计算目录中的文件数,一切都很好。但是,如果我复制文件名strcpy()并传递给其他函数,readdir()会在阅读4个文件后返回NULL

struct A {
    char file_path[100];
    double ave;
};

struct Calc {
    struct A array[10];
    char* max_filename;
    double max;
    char* min_filename;
    double min;
};

int handle() {
    DIR* fd;
    int count = 0;
    struct Calc *calc = calloc(sizeof(struct Calc), 0);

    calc->min = -1;
    calc->min_filename = NULL;
    calc->max = 0;
    calc->max_filename = NULL;

    // open the directory and check
    fd = opendir(DATA_DIR);
    if (fd == NULL)
    {
        printf("Cannot open the directory %s\n", DATA_DIR);
        closedir(fd);
        return -1;
    }

    struct dirent * entry;
    int file_count = 0;
    while ((entry = readdir(fd)) != NULL) {
        if (entry->d_type == DT_REG) { /* If the entry is a regular file */
            file_count++;

            if (count == 9)
            {
                D(calc);
                count = 0;
            }

            struct A *a = &calc->array[count];
            strcpy(a->file_path, entry->d_name);
            calc->array[count].ave = 0;

            C((void*)a);

            count++;
        }
    }   
    printf("Total files: %d\n", file_count);

    closedir(fd);
    D(calc);

    free(calc);
    return 0;
}

int C(void *v)
{
 // code
}

int D(void *v)
{
 // code
}

有谁知道是什么原因引起的?非常感谢你!

1 个答案:

答案 0 :(得分:0)

calc = calloc(sizeof(struct Calc), 0);零看起来错了。                      - kaylum