溫馨提示×

ubuntu readdir如何遞歸讀取目錄

小樊
39
2025-10-18 01:45:32
欄目: 智能運維

在Ubuntu中,你可以使用readdir函數來遞歸地讀取目錄。readdir函數是C語言中的一個庫函數,用于讀取目錄的內容。要遞歸地讀取目錄,你需要結合其他函數,如opendir、closedirstat。

下面是一個簡單的示例,展示了如何使用readdir函數遞歸地讀取目錄:

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

void read_directory_recursive(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;

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

    while ((entry = readdir(dir)) != NULL) {
        char path_buf[PATH_MAX];
        snprintf(path_buf, sizeof(path_buf), "%s/%s", path, entry->d_name);

        if (lstat(path_buf, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
                read_directory_recursive(path_buf);
            }
        } else {
            printf("%s\n", path_buf);
        }
    }

    closedir(dir);
}

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

    read_directory_recursive(argv[1]);

    return EXIT_SUCCESS;
}

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

gcc -o read_directory_recursive read_directory_recursive.c

運行程序,傳入一個目錄作為參數:

./read_directory_recursive /path/to/directory

程序將遞歸地讀取指定目錄及其子目錄,并打印所有文件的路徑。

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