溫馨提示×

Linux readdir如何限制讀取深度

小樊
32
2025-06-16 04:28:24
欄目: 智能運維

在Linux中,readdir函數用于讀取目錄中的文件和子目錄。如果你想要限制readdir的讀取深度,你需要在遞歸遍歷目錄時添加一個計數器來跟蹤當前的深度。

以下是一個簡單的示例,展示了如何在C語言中使用readdir函數并限制讀取深度:

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

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

    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

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

        printf("%*s%s\n", depth * 2, "", entry->d_name);

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

        struct stat statbuf;
        if (stat(child_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            list_directory(child_path, depth + 1);
        }
    }

    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 list_directory.c -o list_directory
./list_directory /path/to/directory 2

/path/to/directory替換為你想要列出內容的目錄,將2替換為你想要限制的最大深度。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女