[英]not able to read directory/files recursively in c
#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);
}
the idea is to list the files and subdirectories from a directory that I send as an argument.这个想法是列出我作为参数发送的目录中的文件和子目录。 It works for few directories and then I get malloc(): corrupted top size Aborted (core dumped) I am probably blind and I dont see the issue, any suggestion?
它适用于几个目录,然后我得到 malloc():corrupted top size Aborted (core dumped) 我可能是盲人,我没有看到问题,有什么建议吗? Thanks in advance!
提前致谢!
The lines线条
struct data *d= (struct data *)malloc(sizeof(struct data *));
struct data *nd= (struct data *)malloc(sizeof(struct data *));
are wrong because you have to allocate for the structure, not for the pointer for the structure.是错误的,因为您必须为结构分配,而不是为结构的指针分配。
They should be他们应该是
struct data *d= malloc(sizeof(*d));
struct data *nd= malloc(sizeof(*nd));
or (if you stick to write type name for sizeof
):或(如果您坚持为
sizeof
编写类型名称):
struct data *d= malloc(sizeof(struct data));
struct data *nd= malloc(sizeof(struct data));
Also note that casting the results of malloc()
in C is discouraged .另请注意, 不鼓励在 C 中转换
malloc()
的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.