c - 递归列表

标签 c recursion ls

我一直在尝试在 C 上实现类似 ls -R 的东西时遇到问题,问题是我需要列表递归地列出从给定目录开始的所有内容,然后对从列表中获得的那些常规文件进行处理。 这是我目前所拥有的:

 void ls(char* path){
    DIR *directory;
    struct dirent *filei;
    struct stat stats;
    directory = opendir(path);
    if (directory != NULL)  
    {
        while ((filei=readdir(directory))!=NULL){
            stat(filei->d_name, &stats);    
            printf(" %s\n", filei->d_name); 
            if (S_ISDIR(stats.st_mode)){
                char *buf = malloc(strlen(path)+strlen(filei->d_name)+2);
                strcpy(buf,path);
                strcat(buf,"/");
                strcat(buf,filei->d_name);
                ls(buf);
            }
        }
        closedir(directory);
    }
    else{
        printf("Error.\n");     
    }
}

它根本不起作用,它显示的文件甚至不在我正在使用的文件夹中。 有什么想法吗? 谢谢。

最佳答案

您不得递归到“.”和“..”条目。您至少会无限递归到同一个目录,或者 up 很糟糕。过滤器:

if (!strcmp(filei->d_name,".") && (!strcmp(filei->d_name,"..")) ls(buf);

您还必须 stat 到完整路径:

char *buf = malloc(strlen(path)+strlen(filei->d_name)+2);
strcpy(buf,path);
strcat(buf,"/");
strcat(buf,filei->d_name);
stat(buf, &stats);
if (S_ISDIR(stats.st_mode)) {
  if (!strcmp(filei->d_name,".") && (!strcmp(filei->d_name,"..")) {
    ls(buf);
  }
}

关于c - 递归列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37915049/

相关文章:

java - 从已排序的双向链表创建二叉搜索树

ruby - 如何在文件夹及其所有子文件夹中搜索某种类型的文件

directory - 无法通过 ls 获取目录的大小

bash - 一旦目录中有 8 个文件,我试图删除目录中最旧的文件

c - 内存同步

C: printf 未执行,可能的编译器优化?

javascript - 如何在加载运行后使用 javascript 提供调用函数的选项

linux - ls -lth | awk '{printf.... 获取文件列表并添加标题

c - 关于具有邻接矩阵表示的非方向图

c - 在计算单词代码上应用 fork() 和 pipe()(或 fifo())