readdir如何处理子目录

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

readdir 是一个用于读取目录内容的函数,它在许多编程语言中都有实现,如 C、C++、PHP 等。要处理子目录,你需要递归地遍历目录结构。以下是一个使用 C 语言的示例,展示了如何使用 readdir 函数处理子目录:

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

void process_directory(const char *path) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        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);

        struct stat path_stat;
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", full_path);
            process_directory(full_path); // 递归处理子目录
        } else {
            printf("File: %s\n", full_path);
            // 在这里处理文件
        }
    }

    closedir(dir);
}

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

    process_directory(argv[1]);
    return 0;
}

这个示例中的 process_directory 函数接受一个目录路径作为参数,然后使用 opendir 打开目录。接着,它使用 readdir 读取目录中的每个条目。对于每个条目,它检查是否是子目录(使用 stat 函数获取文件信息并检查 S_ISDIR 标志)。如果是子目录,它递归地调用 process_directory 函数。如果是文件,你可以在这里处理文件(例如,打印文件名)。

注意:这个示例没有处理符号链接和潜在的循环引用。在实际应用中,你可能需要添加额外的逻辑来处理这些情况。

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

推荐阅读: linux中ls命令的用法