readdir如何实现递归目录遍历

241
2025/4/12 12:32:43
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

readdir 是一个用于读取目录内容的函数,通常在 C 语言中使用。要实现递归目录遍历,你需要结合 opendirreaddirclosedir 函数,并在遇到子目录时递归调用遍历函数。以下是一个简单的示例:

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;

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

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

        snprintf(path_stat.path, sizeof(path_stat.path), "%s/%s", path, entry->d_name);
        if (stat(path_stat.path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", path_stat.path);
            list_directory_contents(path_stat.path);
        } else {
            printf("File: %s\n", path_stat.path);
        }
    }

    closedir(dir);
}

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

    list_directory_contents(argv[1]);
    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,并递归地列出该目录及其子目录中的所有文件和目录。注意,这个程序没有处理符号链接,可能会导致无限循环。要处理符号链接,你需要检查 entry->d_type 是否为 DT_LNK,并根据需要处理。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: linux中mount挂载的作用是什么