温馨提示×

Linux readdir如何实现目录结构输出

小樊
42
2025-10-19 13:09:14
栏目: 智能运维

在 Linux 中,readdir 函数用于读取目录中的文件和子目录。要实现目录结构的输出,你可以使用递归方法遍历目录树。以下是一个简单的示例,展示了如何使用 readdir 函数实现目录结构输出:

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

void print_directory_structure(const char *path, int depth) {
    char buffer[1024];
    struct dirent *dp;
    DIR *dir = opendir(path);

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

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

        snprintf(buffer, sizeof(buffer), "%s/%s", path, dp->d_name);
        struct stat path_stat;
        stat(buffer, &path_stat);

        for (int i = 0; i < depth; i++) {
            printf("-");
        }
        printf("%s\n", dp->d_name);

        if (S_ISDIR(path_stat.st_mode)) {
            print_directory_structure(buffer, depth + 1);
        }
    }

    closedir(dir);
}

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

    print_directory_structure(argv[1], 0);
    return 0;
}

这个程序接受一个目录作为命令行参数,并输出该目录的结构。它使用递归方法遍历目录树,对于每个子目录,它会增加缩进级别并递归调用自身。

编译并运行此程序,如下所示:

gcc directory_structure.c -o directory_structure
./directory_structure /path/to/directory

这将输出指定目录的结构。请注意,这个示例仅适用于类 Unix 系统,如 Linux 和 macOS。

0