温馨提示×

debian readdir如何递归

小樊
37
2026-10-01 10:36:16
栏目: 智能运维

在 Debian(或者说 Linux 下 C/C++ 编程)里,readdir 本身只能读取一个目录下的条目,不支持递归。要实现“递归读取目录”,需要自己写递归函数,在碰到子目录时再次调用 readdir。

下面给你几种常见做法。


一、使用 opendir + readdir + 递归(最基础)

示例(C 语言)

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.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 fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

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

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

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: %s <dir>\n", argv[0]);
        return 1;
    }
    list_dir(argv[1]);
    return 0;
}

编译

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

二、使用 nftw(推荐,系统自带)

Debian 自带 nftw(),专门用来递归遍历目录树,比手写递归安全。

#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <ftw.h>

int cb(const char *path, const struct stat *st, int flag, struct FTW *ftwbuf) {
    if (flag == FTW_D)
        printf("DIR : %s\n", path);
    else if (flag == FTW_F)
        printf("FILE: %s\n", path);
    return 0;
}

int main(int argc, char *argv[]) {
    nftw(argv[1], cb, 20, FTW_PHYS);
    return 0;
}

三、Shell 层面(非 C,但最常用)

如果只是“用 Debian 递归列目录”:

find /path/to/dir

或

ls -R /path/to/dir

四、常见问题提醒

  1. readdir 不区分文件/目录
    • 必须用 stat() 或 lstat() 判断
  2. 符号链接
    • 用 lstat 避免死循环
  3. 权限不足
    • opendir 可能返回 NULL

如果你告诉我:

  • 是 C / C++ / Python / Shell
  • 是否要 处理符号链接 / 权限错误

我可以给你更精确的递归实现。

0 踩