溫馨提示×

Linux readdir如何實現子目錄遍歷

小樊
38
2025-05-20 20:13:51
欄目: 智能運維

在Linux中,使用readdir函數可以實現子目錄遍歷。readdir函數是POSIX標準庫中的一個函數,用于讀取目錄中的條目。以下是一個簡單的示例,展示了如何使用readdir函數遍歷目錄及其子目錄:

#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;
    struct dirent *entry;
    struct stat path_stat;

    dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return;
    }

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

        snprintf(path_stat_path, sizeof(path_stat_path), "%s/%s", path, entry->d_name);
        if (stat(path_stat_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        printf("%s\n", path_stat_path);

        if (S_ISDIR(path_stat.st_mode)) {
            list_directory_contents(path_stat_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;
}

這個程序接受一個目錄路徑作為參數,然后使用readdir函數遍歷該目錄及其子目錄。對于每個目錄條目,我們首先檢查它是否是...,然后使用stat函數獲取條目的詳細信息。如果條目是一個目錄,我們遞歸地調用list_directory_contents函數來遍歷子目錄。

要編譯此程序,請使用以下命令:

gcc -o list_directory_contents list_directory_contents.c

然后運行程序,傳入要遍歷的目錄路徑:

./list_directory_contents /path/to/directory

這將輸出指定目錄及其子目錄中的所有文件和目錄。

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