Warm tip: This article is reproduced from serverfault.com, please click

loops-无法在C中递归读取目录/文件

(loops - not able to read directory/files recursively in c)

发布于 2020-11-28 02:18:56
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>

void listFilesRecursively(void *p);

struct data {
    char path[100];
};

int main(int argc, char* argv[])
{
    // Directory path to list files
    struct data *d= (struct data *)malloc(sizeof(struct data *));
    strcpy(d->path,argv[1]);
    listFilesRecursively(d);   //need to send a struct

    return 0;
}



void listFilesRecursively(void *p)
{
    struct data *d = (struct data *)p;

    char path[100];
    struct dirent *dp;
    DIR *dir = opendir(d->path);

    // Unable to open directory stream
    if (!dir)
        return;

    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            printf("%s\n", d->path);
            struct data *nd= (struct data *)malloc(sizeof(struct data *));

            // Construct new path from our base path
            strcpy(path, d->path);
            strcat(path, "/");
            strcat(path, dp->d_name);
            strcpy(nd->path,path);
            listFilesRecursively(nd);
        }
    }

    closedir(dir);
}

这个想法是列出我作为参数发送的目录中的文件和子目录。它适用于几个目录,然后我得到malloc():损坏的最大大小已中止(核心已转储)我可能是盲目的,我看不到这个问题,有什么建议吗?提前致谢!

Questioner
zancudo
Viewed
0
MikeCAT 2020-11-28 10:21:35

线

    struct data *d= (struct data *)malloc(sizeof(struct data *));

            struct data *nd= (struct data *)malloc(sizeof(struct data *));

是错误的,因为你必须为结构分配,而不是为结构的指针分配。

他们应该是

    struct data *d= malloc(sizeof(*d));

            struct data *nd= malloc(sizeof(*nd));

或(如果你坚持为写下类型名称sizeof):

    struct data *d= malloc(sizeof(struct data));

            struct data *nd= malloc(sizeof(struct data));

另请注意,不建议malloc()在C中强制转换结果