溫馨提示×

如何用readdir實現跨平臺目錄遍歷

小樊
46
2025-07-24 14:41:26
欄目: 編程語言

readdir 是一個用于讀取目錄內容的函數,它在 POSIX 兼容的系統(如 Linux 和 macOS)上可用。要在不同平臺上實現跨平臺的目錄遍歷,你可以使用條件編譯來檢查系統類型,并根據需要調用適當的函數。

以下是一個簡單的示例,展示了如何使用 readdir 實現跨平臺目錄遍歷:

#include <stdio.h>
#include <stdlib.h>

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif

void list_directory_contents(const char *path) {
#if defined(_WIN32) || defined(_WIN64)
    WIN32_FIND_DATA find_file_data;
    HANDLE h_find = INVALID_HANDLE_VALUE;
    char search_path[MAX_PATH];

    snprintf(search_path, MAX_PATH, "%s\\*", path);

    h_find = FindFirstFile(search_path, &find_file_data);
    if (h_find == INVALID_HANDLE_VALUE) {
        printf("Error: Could not open directory\n");
        return;
    }

    do {
        printf("%s\n", find_file_data.cFileName);
    } while (FindNextFile(h_find, &find_file_data) != 0);

    FindClose(h_find);
#else
    DIR *dir = opendir(path);
    struct dirent *entry;

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

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
#endif
}

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

在這個示例中,我們首先檢查是否在 Windows 平臺上(使用 _WIN32_WIN64 宏)。如果是 Windows 平臺,我們使用 FindFirstFileFindNextFile 函數來遍歷目錄。否則,我們在 POSIX 兼容的系統上使用 opendir、readdirclosedir 函數。

要編譯此代碼,請根據您的平臺選擇適當的編譯器標志。例如,在 Linux 或 macOS 上,您可以使用以下命令:

gcc -o list_directory_contents list_directory_contents.c

在 Windows 上,您可以使用 MinGW 或 Visual Studio 編譯器。

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