C++中OS.walk的替代方案

7 投票
2 回答
3061 浏览
提问于 2025-04-17 17:28

我想写一个C++程序,从一个文件夹里读取一些文件,文件的数量是不确定的。我知道有一个Python的实现方法叫做OS.walk,可以完美地完成这个任务:

Python OS.walk

有没有人知道怎么用C++实现这个OS.walk的功能呢?

提前谢谢大家!

2 个回答

4

用标准的C++现在是做不到的。

不过,你可以使用Boost.Filesystem(可以找找recursive_directory_iterator这个东西),它可能会在未来的C++版本中被包含进来。

12
#include <boost/filesystem.hpp>
#include <iostream>

int main()
{
 boost::filesystem::path path = boost::filesystem::current_path();
 boost::filesystem::recursive_directory_iterator itr(path);
 while (itr != boost::filesystem::recursive_directory_iterator())
 {
   std::cout << itr->path().string() << std::endl;
   ++itr;
 }
}

这段内容直接来自于 http://www.deanwarrenuk.com/2012/09/how-to-recursively-walk-folder-in-c.html

这个网站很好地解释了为什么你需要使用boost库来隐藏不同文件系统之间的差异。

撰写回答