linux

Linux readdir如何处理子目录递归

小樊
35
2025-07-08 10:24:06
栏目: 智能运维

在Linux中,readdir函数用于读取目录中的条目。但是,readdir本身并不会递归地处理子目录。要实现递归处理子目录,你需要自己编写递归函数来遍历目录结构。

以下是一个使用C语言编写的示例,展示了如何使用readdiropendir函数递归地处理子目录:

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

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

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

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

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

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

        if (S_ISDIR(statbuf.st_mode)) {
            process_directory(path_buf); // 递归处理子目录
        } else {
            // 处理文件
            printf("File: %s\n", path_buf);
        }
    }

    closedir(dir);
}

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

    process_directory(argv[1]);

    return 0;
}

这个程序接受一个目录作为命令行参数,并递归地处理该目录及其所有子目录中的文件。对于每个文件,它将打印文件的完整路径。你可以根据需要修改process_directory函数以执行所需的操作。

0
看了该问题的人还看了