溫馨提示×

如何用copendir實現目錄遞歸遍歷

小樊
65
2025-03-23 07:05:18
欄目: 編程語言

opendir 函數用于打開一個目錄流,而 readdir 函數用于讀取目錄中的條目。要實現目錄的遞歸遍歷,你需要結合這兩個函數,并對子目錄進行遞歸調用。

以下是一個使用 opendirreaddir 實現目錄遞歸遍歷的示例代碼(C語言):

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

void list_directory_contents(const char *path) {
    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[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

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

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", full_path);
            list_directory_contents(full_path);
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dir);
}

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

    list_directory_contents(argv[1]);
    return EXIT_SUCCESS;
}

這個程序接受一個命令行參數作為要遍歷的目錄路徑。list_directory_contents 函數會打開目錄,讀取其中的條目,并檢查每個條目是文件還是子目錄。如果是子目錄,它會遞歸調用自身以繼續遍歷子目錄的內容。

編譯并運行這個程序,傳入一個目錄路徑作為參數,它將打印出該目錄及其所有子目錄中的文件和目錄。

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