2016-11-25 55 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)不以任何特定的順序返回條目,所以沒有辦法有,只要你想命令他們。你最好的選擇是自己做訂購/洗牌。

相關問題