温馨提示×

debian copendir如何遍历子目录

小樊
35
2026-10-04 00:13:09
栏目: 智能运维

在 Debian(或任何 Linux 系统)下,使用 C 语言通过 opendir / readdir 遍历子目录(递归遍历目录树),核心思路是:

  1. 用 opendir() 打开目录
  2. 用 readdir() 读取每一项
  3. 判断 d_type 或 stat() 是否为目录
  4. 如果是子目录,递归调用自己

一、基本示例(递归遍历目录)

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

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

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

        // 构造完整路径
        char full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        // 判断是否为目录
        if (entry->d_type == DT_DIR) {
            printf("目录: %s\n", full_path);
            list_dir(full_path);  // 递归
        } else {
            printf("文件: %s\n", full_path);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "用法: %s <目录>\n", argv[0]);
        return 1;
    }
    list_dir(argv[1]);
    return 0;
}

二、编译与运行(Debian)

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

三、注意事项(很重要)

1️⃣ d_type 不一定可靠

在某些文件系统(如某些 NFS)上:

entry->d_type == DT_UNKNOWN

✅ 更稳妥的方式是用 stat():

struct stat st;
stat(full_path, &st);
if (S_ISDIR(st.st_mode)) {
    list_dir(full_path);
}

2️⃣ 符号链接处理

避免死循环:

lstat(full_path, &st);
if (S_ISLNK(st.st_mode)) {
    // 跳过符号链接目录
}

3️⃣ 路径长度安全

真实项目建议用 realpath() 或动态分配路径。


四、非递归方式(可选)

如果你不想用递归,可以用:

  • 栈 / 队列
  • fts_open()(更专业,推荐)

示例(fts 方式)

#include <fts.h>

适合大规模目录遍历。


五、总结

✅ Debian 下用 opendir 遍历子目录 =
opendir → readdir → 判断目录 → 递归

如果你需要:

  • 只遍历一层
  • 按文件类型过滤
  • 统计文件数
  • 用 nftw()

可以继续问我。

0 踩