2016-11-25 59 views
0

以下代码对递归遍历给定目录并每次以相同顺序打印其内容。非确定性执行boost文件系统directory_iterator

是否可以改变目录迭代器以随机方式打印目录内容(即不使用矢量来存储结果,然后随机打印矢量内容)?

#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; 
     } 
    } 
} 

}

+0

除非迭代器自己进行一些排序,否则顺序将是操作系统为您提供文件条目的顺序,很可能是它们存储在磁盘表中的顺序。如果你想要另一个订单,那么除了中间向量之外真的没有别的办法。 –

回答

1

大多数操作系统(例如Windows的FindFirstFile)不以任何特定的顺序返回条目,所以没有办法有,只要你想命令他们。你最好的选择是自己做订购/洗牌。

相关问题