发布于2026-07-06 阅读(0)
扫一扫,手机访问
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,换成你实际要读取的目录路径就行。就这么简单。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8