温馨提示×

Linux readdir的递归目录读取

小樊
39
2025-11-21 16:58:55
栏目: 智能运维

在Linux中,要实现递归目录读取,可以使用opendir()readdir()closedir()函数。下面是一个简单的示例,展示了如何使用这些函数递归地读取目录及其子目录中的所有文件和文件夹:

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

void read_directory(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;
    char fullpath[PATH_MAX];

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

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

        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

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

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

    closedir(dir);
}

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

    read_directory(argv[1]);

    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,然后递归地读取该目录及其子目录中的所有文件和文件夹。对于每个文件或文件夹,它将打印其完整路径。

要编译此程序,请使用以下命令:

gcc -o recursive_directory_listing recursive_directory_listing.c

然后运行程序,传递要读取的目录作为参数:

./recursive_directory_listing /path/to/directory

这将输出指定目录及其子目录中的所有文件和文件夹。

0