温馨提示×

ubuntu copendir能递归子目录吗

小樊
45
2026-09-20 22:19:27
栏目: 智能运维

在 Ubuntu / Linux 下,opendir() 本身不能递归子目录。

说明

  • opendir() 只是打开一个目录,返回一个 DIR *
  • 它只能配合 readdir() 读取当前目录下的条目
  • 是否进入子目录,需要你在代码里自己判断并递归调用

典型做法

#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.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 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);
            list_dir(full);   // 递归子目录
        } else {
            printf("File: %s\n", full);
        }
    }
    closedir(dir);
}

补充

  • opendir / readdir 是 POSIX API
  • 若你只是想在 shell 里递归,用:
    find path
    
    或
    ls -R path
    

如果你是在写 C / C++ 程序 或 脚本,可以告诉我具体场景,我可以给你更合适的示例。

0 踩