readdir如何实现跨平台文件操作
作者:小宇宙叶知秋
时间:2026-07-06
浏览:0
readdir函数是Unix系统(Linux/macOS)的POSIX接口,无法直接用于Windows。跨平台解决方案推荐C++17的std::filesystem标准库,也可选用Boost.Filesystem作为后备,两者均提供简洁、统一的目录遍历功能。
readdir 这个函数,熟悉 POSIX 标准的朋友应该不陌生,它在 Linux 和 macOS 这类 Unix-like 系统上非常常用,主要负责读取目录内容。但问题来了:如果要把同样的功能搬到 Windows 上,直接套用 readdir 肯定行不通。那怎么办?其实,C++17 引入的 库就是跨平台的首选,实在不行,Boost.Filesystem 也是稳妥的后备方案。

先看 C++17 的写法。用 std::filesystem 处理目录遍历,代码简洁得让人舒服:
#include
#include
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;
}
如果你还在用较旧的 C++ 标准,或者项目中已经集成了 Boost,那 Boost.Filesystem 的方案同样可靠:
#include
#include
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,换成你实际要读取的目录路径就行。就这么简单。
作者最新文章
极度公式
2026-09-16 17:43
索尼WH-1000XM4C发布:复刻经典折叠设计并升级现代接口
2026-09-08 19:10
PDF转TXT操作步骤与转换后内容核对指南
2026-09-04 18:03
Photoshop安装失败或启动异常:系统要求、安装流程与故障排查指南
2026-09-03 06:04
PDF文件体积过大如何压缩及压缩后清晰度检查方法
2026-09-02 19:30
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































