linux

Linux readdir怎样处理子目录

小樊
41
2025-12-21 07:08:36
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。要处理子目录,你需要递归地遍历目录结构。以下是一个简单的示例,展示了如何使用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;
    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);
            process_directory(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;
    }

    process_directory(argv[1]);

    return EXIT_SUCCESS;
}

这个示例程序接受一个目录路径作为命令行参数,然后使用readdir函数读取目录中的条目。对于每个条目,它检查是否是子目录。如果是子目录,它会递归地调用process_directory函数来处理子目录。如果不是子目录,它会打印文件名。

注意:这个示例程序没有处理符号链接和其他特殊文件类型。在实际应用中,你可能需要根据你的需求对这些情况进行额外的处理。

0
看了该问题的人还看了