linux

Linux readdir如何限制目录深度

小樊
31
2025-06-26 07:36:12
栏目: 智能运维

在Linux中,使用readdir函数读取目录时,可以通过递归遍历目录并检查当前目录深度来限制目录深度。以下是一个简单的示例,展示了如何在C语言中使用readdir函数限制目录深度:

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

void list_directory(const char *path, int depth) {
    if (depth < 0) {
        return;
    }

    DIR *dir = opendir(path);
    if (!dir) {
        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 statbuf;
        if (stat(full_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            printf("%*s%s/\n", depth * 2, "", entry->d_name);
            list_directory(full_path, depth - 1);
        } else {
            printf("%*s%s\n", depth * 2, "", entry->d_name);
        }
    }

    closedir(dir);
}

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

    const char *path = argv[1];
    int depth = atoi(argv[2]);

    list_directory(path, depth);

    return 0;
}

在这个示例中,list_directory函数接受一个目录路径和一个深度值。它会递归地遍历目录,并在每次递归调用时减少深度值。当深度值小于0时,递归停止。

要编译并运行此程序,请将其保存为list_directory.c,然后使用以下命令:

gcc -o list_directory list_directory.c
./list_directory /path/to/directory 2

/path/to/directory替换为您要列出目录的路径,将2替换为您要限制的最大深度。

0
看了该问题的人还看了