readdir 是一个用于读取目录内容的函数,它在 POSIX 标准中定义,因此在 Unix-like 系统(如 Linux 和 macOS)上可用。要在 Windows 上实现类似的跨平台文件操作,你可以使用 C++17 中引入的 <filesystem> 库或者使用第三方库,如 Boost.Filesystem。
以下是使用 C++17 <filesystem> 库实现跨平台目录读取的示例:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
std::string path = "your_directory_path_here";
if (fs::exists(path) && fs::is_directory(path)) {
for (const auto& entry : fs::directory_iterator(path)) {
std::cout << entry.path() << std::endl;
}
} else {
std::cerr << "The specified path does not exist or is not a directory." << std::endl;
}
return 0;
}
如果你使用的是 Boost.Filesystem,示例代码如下:
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main() {
std::string path = "your_directory_path_here";
if (fs::exists(path) && fs::is_directory(path)) {
for (fs::directory_iterator it(path); it != fs::directory_iterator(); ++it) {
std::cout << it->path() << std::endl;
}
} else {
std::cerr << "The specified path does not exist or is not a directory." << std::endl;
}
return 0;
}
这两个示例都会遍历指定目录中的所有文件和子目录,并将它们的路径输出到控制台。注意,你需要根据实际情况替换 your_directory_path_here 为你要读取的目录路径。