溫馨提示×

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

小樊
79
2025-03-31 08:33:13
欄目: 智能運維

在Linux中,opendir、readdirclosedir 是用于遍歷目錄的標準C庫函數。然而,這些函數本身并不支持遞歸遍歷目錄。要實現遞歸遍歷,你需要編寫一個遞歸函數來處理子目錄。下面是一個示例代碼,演示如何使用這些函數遞歸遍歷目錄:

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;

    // 打開目錄
    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    // 遍歷目錄中的條目
    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);

        // 獲取文件/目錄的信息
        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>\n", argv[0]);
        return EXIT_FAILURE;
    }

    list_directory_contents(argv[1]);

    return EXIT_SUCCESS;
}

代碼說明:

  1. 打開目錄:使用 opendir 函數打開指定路徑的目錄。

  2. 讀取目錄條目:使用 readdir 函數讀取目錄中的每個條目。

  3. 跳過特殊條目:忽略當前目錄(.)和父目錄(..)。

  4. 構建完整路徑:使用 snprintf 構建每個條目的完整路徑。

  5. 獲取文件/目錄信息:使用 stat 函數獲取文件或目錄的信息,以便判斷它是文件還是目錄。

  6. 遞歸處理子目錄:如果條目是一個目錄(通過 S_ISDIR 判斷),則遞歸調用 list_directory_contents 函數。

  7. 關閉目錄:使用 closedir 函數關閉目錄。

編譯和運行:

將上述代碼保存為 recursive_directory_traversal.c,然后使用以下命令編譯和運行:

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

替換 /path/to/directory 為你想要遍歷的目錄路徑。這個程序將遞歸地列出指定目錄及其所有子目錄中的文件和目錄。

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