linux

Linux readdir怎样支持递归遍历

小樊
36
2025-06-03 23:39:10
栏目: 智能运维

在Linux中,readdir函数本身并不直接支持递归遍历目录。它主要用于读取指定目录下的文件和子目录。要实现递归遍历,你需要自己编写一个递归函数来处理这个问题。

以下是一个使用C语言编写的递归遍历目录的示例:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.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;
}

这个程序接受一个目录作为命令行参数,并递归地列出该目录下的所有文件和子目录。请注意,这个示例没有处理符号链接和其他特殊文件类型,你可能需要根据实际需求进行相应的修改。

0
看了该问题的人还看了