readdir 是一个用于读取目录内容的函数,它在 POSIX 标准中定义,因此在 Unix、Linux 和 macOS 等类 Unix 系统上可用。要在 Windows 上实现类似的功能,可以使用 FindFirstFile 和 FindNextFile 函数。
以下是一个简单的示例,展示了如何在 Unix 和 Windows 上使用 readdir 和 FindFirstFile/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 系统上编译和运行了。