温馨提示×

debian readdir如何递归子目录

小樊
39
2026-09-28 12:39:59
栏目: 智能运维

在 Debian(以及一般的 Linux)下,如果你问的是 readdir 这个函数如何递归遍历子目录,通常是指 C 语言中的 readdir() + opendir() / stat() 来实现递归目录遍历。

下面给你几种常见做法。


一、核心思路(C 语言 readdir 递归)

  1. opendir() 打开目录
  2. readdir() 逐个读取目录项
  3. 用 stat() 或 lstat() 判断是否为目录
  4. 如果是目录且不是 . 或 ..,递归调用自己

二、最简示例(递归 readdir)

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

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) return;

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        char fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        struct stat st;
        stat(fullpath, &st);

        if (S_ISDIR(st.st_mode)) {
            printf("DIR: %s\n", fullpath);
            list_dir(fullpath);  // 递归
        } else {
            printf("FILE: %s\n", fullpath);
        }
    }
    closedir(dir);
}

int main(int argc, char *argv[]) {
    list_dir(argv[1]);
    return 0;
}

编译:

gcc readdir_recursive.c -o readdir_recursive
./readdir_recursive /path/to/dir

三、注意事项(Debian / Linux)

1. 符号链接

  • stat() 会跟随符号链接
  • 如果避免循环递归,用 lstat()
lstat(fullpath, &st);
if (S_ISLNK(st.st_mode)) {
    // 符号链接
}

2. 避免递归过深

  • 可用 ftw() 或 nftw()(更专业)

四、更推荐的方式(系统提供)

1. nftw()(推荐)

#include <ftw.h>
#include <stdio.h>

int fn(const char *path, const struct stat *st, int flag, struct FTW *ftwbuf) {
    printf("%s\n", path);
    return 0;
}

int main() {
    nftw(".", fn, 20, FTW_PHYS);
    return 0;
}

2. 命令行方式(非 C)

如果你只是想在 Debian 上递归列目录:

find /path -type f
ls -R /path

五、总结

方法 是否递归 推荐度
readdir + 递归 ✅ ⭐⭐⭐
nftw ✅ ⭐⭐⭐⭐⭐
find ✅ ⭐⭐⭐⭐⭐

如果你是想 写内核模块 / 使用 readdir 系统调用 / 在某个特定语言(Python/Shell)里递归,可以告诉我具体场景。

0 踩