溫馨提示×

readdir在Linux系統中如何實現遞歸讀取

小樊
46
2025-10-06 19:56:50
欄目: 智能運維

在Linux系統中,readdir函數本身并不支持遞歸讀取目錄

#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) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        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)) {
            if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
                list_directory_contents(full_path);
            }
        } else {
            printf("%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;
}

這個程序接受一個目錄路徑作為參數,并遞歸地列出該目錄及其所有子目錄中的文件。list_directory_contents函數首先打開目錄,然后使用readdir讀取目錄中的每個條目。對于每個條目,它使用stat函數獲取文件的狀態信息,然后檢查是否為目錄。如果是目錄(并且不是當前目錄.或上級目錄..),則遞歸調用list_directory_contents。如果不是目錄,則打印文件的完整路徑。

要編譯此程序,請將其保存為list_dir.c,然后運行以下命令:

gcc -o list_dir list_dir.c

現在,您可以使用以下命令運行程序:

./list_dir /path/to/directory

這將遞歸地列出指定目錄及其所有子目錄中的文件。

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