温馨提示×

如何用readdir实现跨平台目录遍历

小樊
51
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 兼容的系统上使用 opendirreaddirclosedir 函数。

要编译此代码,请根据您的平台选择适当的编译器标志。例如,在 Linux 或 macOS 上,您可以使用以下命令:

gcc -o list_directory_contents list_directory_contents.c

在 Windows 上,您可以使用 MinGW 或 Visual Studio 编译器。

0