以下代码递归地遍历给定目录并每次以相同顺序打印其内容。
是否可以改变目录迭代器以随机方式打印目录内容(而不是使用 vector 存储结果然后随机打印 vector 内容)?
#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
int main(int argc, char** argv)
{
boost::filesystem::path dataPath("/home/test/");
boost::filesystem::recursive_directory_iterator endIterator;
// Traverse the filesystem and retrieve the name of each root object found
if (boost::filesystem::exists(dataPath) && boost::filesystem::is_directory(dataPath)) {
for (static boost::filesystem::recursive_directory_iterator directoryIterator(dataPath); directoryIterator != endIterator;
++directoryIterator) {
if (boost::filesystem::is_regular_file(directoryIterator->status())) {
std::string str = directoryIterator->path().string();
cout << str << endl;
}
}
}
最佳答案
大多数操作系统(例如 Windows 的 FindFirstFile )不会以任何特定顺序返回条目,因此无法按照您的意愿对它们进行排序。最好的办法是自己进行排序/洗牌。
关于c++ - boost 文件系统 directory_iterator 的非确定性执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40801801/