温馨提示×

ubuntu copendir能遍历子目录吗

小樊
35
2026-10-05 14:29:12
栏目: 智能运维

在 Ubuntu(Linux)下,opendir 本身不能递归遍历子目录,它只能打开并读取某一个目录里的条目(文件和子目录名)。

具体说明如下:

1. opendir 的作用

DIR *opendir(const char *name);
  • 打开一个目录
  • 返回一个 DIR* 句柄
  • 配合 readdir 使用,只能读取当前目录下的内容

2. 如何“遍历子目录”

要遍历子目录,需要自己写递归逻辑:

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

3. 总结

  • ✅ opendir 能打开目录
  • ❌ opendir 不会自动进入子目录
  • ✅ 遍历子目录需要:opendir + readdir + stat + 递归

如果你愿意,我也可以给你一个 不用递归的栈/队列实现,或者 用 nftw 更简单的方法。

0 踩