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,换成你实际要读取的目录路径就行。就这么简单。
作者最新文章
Excel单元格内换行教程:Alt+Enter快捷键与自动换行设置
2026-10-30 18:49
3DMax材质贴图浏览器怎么打开
2026-10-29 12:08
blender几何节点功能怎么开启教程界面入口与启用步骤
2026-10-18 13:20
PDF删页删错怎么找回?PDF删页报参数错误怎么办?
2026-10-17 11:21
蚂蚁庄园1月18日:人们常用砸锅来形容事情没办成猜猜最早源于哪个行业
2026-09-24 16:59
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
























