温馨提示×

debian readdir如何递归读取目录

小樊
35
2025-12-08 13:47:39
栏目: 智能运维

在 Debian 系统中,你可以使用 readdir 函数来递归地读取目录。readdir 函数是 POSIX 标准库中的一个函数,用于读取目录项。要递归地读取目录,你需要编写一个递归函数来遍历目录树。

以下是一个使用 C 语言编写的示例程序,演示如何使用 readdir 函数递归地读取目录:

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

void read_directory_recursive(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;

    if (!(dir = opendir(path))) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;

        char full_path[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        if (lstat(full_path, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            read_directory_recursive(full_path);
        } else {
            printf("%s\n", full_path);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return EXIT_FAILURE;
    }

    read_directory_recursive(argv[1]);

    return EXIT_SUCCESS;
}

将此代码保存为 read_directory_recursive.c,然后使用以下命令编译它:

gcc -o read_directory_recursive read_directory_recursive.c

现在,你可以使用以下命令运行程序,递归地读取指定目录:

./read_directory_recursive /path/to/directory

程序将输出目录及其子目录中的所有文件。

0