温馨提示×

debian copendir能遍历子目录吗

小樊
45
2026-09-09 23:38:02
栏目: 智能运维

在 Debian(以及所有符合 POSIX 标准的系统)里,opendir 本身不能遍历子目录,它只能打开一个目录,并配合 readdir 读取该目录下的直接条目(包括子目录名,但不会自动进入子目录)。

关键点

  • opendir(dir):打开一个目录
  • readdir(dp):读取目录项(文件 / 子目录 / 符号链接等)
  • 不会递归
  • 要遍历子目录,需要你自己递归调用 opendir

示例(C 语言,递归遍历)

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

void walk(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 full[1024];
        snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);

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

        if (S_ISDIR(st.st_mode)) {
            printf("DIR: %s\n", full);
            walk(full);  // 递归遍历子目录
        } else {
            printf("FILE: %s\n", full);
        }
    }
    closedir(dir);
}

int main() {
    walk(".");
    return 0;
}

如果你只是想“用命令”

  • find /path:递归遍历
  • ls -R:递归列出

总结

opendir 可以“看到”子目录
opendir 不会自动遍历子目录
✅ 遍历子目录必须手动递归

如果你是在写 C / C++ / shell / Python,可以告诉我语言,我可以给你更合适的示例。

0