溫馨提示×

readdir如何跨平臺使用

小樊
44
2025-08-26 13:44:48
欄目: 編程語言

readdir 是一個用于讀取目錄內容的函數,它在 POSIX 標準中定義,因此在 Unix、Linux 和 macOS 等類 Unix 系統上可用。要在 Windows 上實現類似的功能,可以使用 FindFirstFileFindNextFile 函數。

以下是一個簡單的示例,展示了如何在 Unix 和 Windows 上使用 readdirFindFirstFile/FindNextFile 函數讀取目錄內容:

Unix/Linux/macOS:

#include <stdio.h>
#include <dirent.h>

int main() {
    DIR *dir;
    struct dirent *entry;

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

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

    closedir(dir);
    return 0;
}

Windows:

#include <stdio.h>
#include <windows.h>

int main() {
    WIN32_FIND_DATA findFileData;
    HANDLE hFind;

    hFind = FindFirstFile(".", &findFileData);
    if (hFind == INVALID_HANDLE_VALUE) {
        printf("FindFirstFile failed\n");
        return 1;
    }

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

    FindClose(hFind);
    return 0;
}

為了實現跨平臺兼容性,可以使用條件編譯來根據不同的操作系統選擇合適的函數:

#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#endif

int main() {
#ifdef _WIN32
    WIN32_FIND_DATA findFileData;
    HANDLE hFind;

    hFind = FindFirstFile(".", &findFileData);
    if (hFind == INVALID_HANDLE_VALUE) {
        printf("FindFirstFile failed\n");
        return 1;
    }

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

    FindClose(hFind);
#else
    DIR *dir;
    struct dirent *entry;

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

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

    closedir(dir);
#endif
    return 0;
}

這樣,代碼就可以在 Unix 和 Windows 系統上編譯和運行了。

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