c - 在 C 中递归地打印 Linux 中路径中的所有文件和文件夹

标签 c recursion directory-listing

我一直在尝试学习如何使用函数与系统上的路径进行交互,但我想我一开始就陷入困境。

我特别搜索了网络和 stackoverflow,但找不到像我想做的那样的基本实现。还有一些其他问题,与我的类似,但我觉得它们不像我的那样简单且适合初学者。

这是代码,该代码仅打印给定路径中的文件,以及“.”和“..”

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

void listdir(DIR *c);

int main()
{

    DIR* root_d;
    root_d = opendir("/home/foo/Desktop/testx");
    listdir(root_d);

}

void listdir(DIR *c){
    DIR* current = c;
    struct dirent *curr_ent;
    if((curr_ent =readdir(current)) != NULL && curr_ent->d_type == DT_DIR){
        listdir(current);
    }
    printf("%s\n", curr_ent->d_name);
    return;
}

我做错了什么?

最佳答案

它的工作原理完全正确,您只是忘记了排除 ...。这两个“虚拟”目录存在于所有目录中。 . 是“self”的快捷方式,..parent 的快捷方式。

例如如果您执行了 listdir('.'),那么您将继续循环,因为您在 . 中执行 opendir 时得到的第一件事就是code> 是另一个 .,它指向完全相同的位置。

简而言之,您需要以下伪代码:

if (dir != '.' && dir != '..' && is_dir(dir)) {
    listdir(dir);
}

关于c - 在 C 中递归地打印 Linux 中路径中的所有文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29401653/

相关文章:

powershell - 为什么Test-Connection强制枚举重解析点?

c++ - 如何使用 C++ 列出 Windows 目录中的所有 CSV 文件?

c - unsigned 和 int 陷阱

c - 如何将文件中的字符转换为ascii整数转换为数组?

C - 从递归返回后指针值发生变化

c++ - 在 C++ 中使用递归返回值

c - 递归列出目录

c - ACSL - 无法证明功能

c - mlockall 的这种用法正确吗?

javascript - 从对象属性递归生成文件路径