readdir 是一个用于读取目录内容的函数,它在 POSIX 标准中定义,因此在 Unix-like 系统(如 Linux 和 macOS)上可用。要在 Windows 上实现类似的功能,可以使用 Windows API 函数 FindFirstFile 和 FindNextFile。下面是一个简单的跨平台目录读取示例,使用 C++ 编写:
#include <iostream>
#include <string>
#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
void list_directory_contents(const std::string& path) {
#ifdef _WIN32
WIN32_FIND_DATA find_data;
HANDLE h_find = FindFirstFile((path + "\\*").c_str(), &find_data);
if (h_find == INVALID_HANDLE_VALUE) {
std::cerr << "Error: Cannot open directory." << std::endl;
return;
}
do {
std::cout << find_data.cFileName << std::endl;
} while (FindNextFile(h_find, &find_data) != 0);
FindClose(h_find);
#else
DIR* dir = opendir(path.c_str());
if (dir == nullptr) {
std::cerr << "Error: Cannot open directory." << std::endl;
return;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
std::cout << entry->d_name << std::endl;
}
closedir(dir);
#endif
}
int main() {
std::string path = "."; // 当前目录
list_directory_contents(path);
return 0;
}
这个示例中,我们定义了一个名为 list_directory_contents 的函数,它接受一个表示目录路径的字符串。根据编译目标平台(Windows 或其他),我们使用相应的 API 函数来读取目录内容。在 Windows 上,我们使用 FindFirstFile 和 FindNextFile,而在其他平台上,我们使用 opendir 和 readdir。
要编译此代码,请确保在 Windows 上使用支持 Windows API 的编译器(如 Visual Studio),在其他平台上使用支持 POSIX 标准的编译器(如 GCC 或 Clang)。