溫馨提示×

Linux readdir如何實現遞歸讀取

小樊
46
2025-04-26 15:00:56
欄目: 智能運維

在Linux中,readdir函數用于讀取目錄中的條目。但是,readdir本身并不支持遞歸讀取子目錄。要實現遞歸讀取,你需要自己編寫一個遞歸函數來遍歷目錄結構。以下是一個簡單的示例,展示了如何使用readdiropendir函數遞歸地讀取目錄及其子目錄中的所有文件:

#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;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", path_stat.path);
            list_directory_contents(path_stat.path);
        } else {
            printf("File: %s\n", 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;
}

這個程序接受一個目錄路徑作為參數,并遞歸地列出該目錄及其所有子目錄中的文件。請注意,這個示例沒有處理符號鏈接、權限問題和其他可能的錯誤情況。在實際應用中,你可能需要根據具體需求對其進行修改和擴展。

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