【发布时间】:2017-01-25 13:37:18
【问题描述】:
以下代码打开一个路径并递归地读取目录并打印其中的文件。目前它只打印目录的路径,然后打印其中的每个文件,但我想实现一个链接列表,其中包含 1 个 char* 变量,其中包含访问的每个文件的完整路径。
代码如下:
#include <dirent.h>
#include <stdio.h>
#include <string.h>
void show_dir_content(char * path)
{
DIR * d = opendir(path);
if(d==NULL) return;
struct dirent * dir;
while ((dir = readdir(d)) != NULL)
{
if(dir-> d_type != DT_DIR) // if the type is not directory just print it
printf("\t%s\n",dir->d_name);
else
if(dir -> d_type == DT_DIR && strcmp(dir->d_name,".")!=0 && strcmp(dir->d_name,"..")!=0 ) // if it is a directory
{
char d_path[255]; // here I am using sprintf which is safer than strcat
sprintf(d_path, "%s/%s", path, dir->d_name);
printf("%s\n",d_path);
show_dir_content(d_path);
}
}
closedir(d);
}
int main(int argc, char **argv)
{
show_dir_content(argv[1]);
return(0);
}
用于链表的结构可以很简单,例如:
typedef struct search search;
struct search {
char *path;
char *fileName;
char *fullPathToFile;
search *next;
};
我只是很难为结构使用 mallocs 并在递归函数中创建实际的链表。任何帮助表示赞赏。
【问题讨论】:
-
太宽泛的问题。请具体说明您遇到的确切问题。
-
@user694733 我的问题在问题的末尾指定。
-
您列出了模糊的问题清单。您设法定义了结构类型。你的下一步是什么?假设它使用
malloc为其分配内存,你遇到了什么问题?编译错误信息?将您的问题分解为更小的问题,直到您有一个明确的问题我们可以回答。 -
@user694733 好的,所以我试着不那么含糊。 Here is the new question我问的更详细一点。你介意看看吗?
标签: c recursion linked-list filesystems