【问题标题】:not able to read directory/files recursively in c无法在c中递归地读取目录/文件
【发布时间】:2021-03-10 17:39:17
【问题描述】:
#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():corrupted top size 中止(核心转储) 我可能是盲人,我没有看到问题,有什么建议吗?提前致谢!

【问题讨论】:

  • 您可以做的一件让您的生活更轻松的事情是摆脱对malloc() 的调用,只需将您的struct data 对象声明为堆栈变量,例如struct data d; memset(&amp;d, 0, sizeof(d)); strcpy(d.path,argv[1]); listFilesRecursively(&amp;d);

标签: c loops recursion malloc structure


【解决方案1】:

线条

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

还要注意,在 C 中转换 malloc() 的结果是 discouraged

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 2021-01-29
    • 2018-03-05
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    相关资源
    最近更新 更多