溫馨提示×

如何在Debian中使用readdir進行遞歸遍歷

小樊
37
2025-05-09 21:31:32
欄目: 智能運維

在Debian中,你可以使用C語言編寫一個程序來實現遞歸遍歷目錄(使用readdir函數)

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

void list_directory_contents(const char *path);

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

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;
    char full_path[PATH_MAX];

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

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

        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        if (lstat(full_path, &path_stat) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(path_stat.st_mode)) {
            printf("Directory: %s\n", full_path);
            list_directory_contents(full_path);
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dir);
}

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

gcc -o recursive_readdir recursive_readdir.c

現在,你可以運行這個程序來遞歸遍歷目錄:

./recursive_readdir /path/to/directory

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

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