温馨提示×

debian copendir能递归遍历吗

小樊
34
2026-10-04 00:25:08
栏目: 智能运维

在 Debian(以及其它 Linux 系统)里,opendir 本身不能递归遍历目录。

简单说明

  • opendir():只是打开一个目录,返回一个 DIR *
  • readdir():读取该目录下的直接成员(文件和子目录)
  • 它不会自动进入子目录

想递归遍历,需要自己做

常见做法:

  1. opendir + readdir
  2. 对每个条目用 stat / lstat
  3. 如果是目录,就再次 opendir(递归或栈/队列)

示例(C 递归遍历)

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

void traverse(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;
        lstat(full, &st);

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

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

不想自己写?

  • 命令行:find
  • C 库:fts_open / nftw(比手写递归更安全)

一句话总结

opendir 只能打开一层目录,递归遍历必须自己实现或用更高层 API。

如果你是想问 shell / Python / find 命令 的递归,也可以告诉我。

0 踩