溫馨提示×

ubuntu readdir如何限制讀取深度

小樊
97
2025-02-15 11:28:08
欄目: 智能運維

在Ubuntu中,使用readdir函數讀取目錄時,可以通過遞歸遍歷目錄并檢查當前深度來限制讀取深度。以下是一個簡單的C語言示例,展示了如何使用readdir函數限制讀取深度:

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

void read_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;
        }

        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("Directory: %s\n", full_path);
            read_directory(full_path, depth - 1);
        } else {
            printf("File: %s\n", full_path);
        }
    }

    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]);

    read_directory(path, depth);

    return 0;
}

在這個示例中,read_directory函數接受兩個參數:要讀取的目錄路徑和最大深度。它會遞歸地遍歷目錄,并在達到最大深度時停止遞歸。

編譯并運行此程序:

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

/path/to/directory替換為要讀取的目錄路徑,將2替換為所需的最大深度。

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