溫馨提示×

CentOS readdir的遞歸讀取方法

小樊
41
2025-05-31 07:10:14
欄目: 智能運維

在 CentOS 系統中,你可以使用 readdir 函數來遞歸地讀取目錄。以下是一個使用 C 語言編寫的示例程序,展示了如何使用 readdir 函數遞歸地讀取目錄及其子目錄中的所有文件和文件夾:

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

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

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

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

        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)) {
            read_directory(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 1;
    }

    read_directory(argv[1]);
    return 0;
}

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

gcc -o read_directory read_directory.c

現在,你可以使用以下命令運行程序,其中 <directory> 是要遞歸讀取的目錄路徑:

./read_directory <directory>

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

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