2017-03-03 47 views
1

這是boost directory_iterator example - how to list directory files not recursive的後續問題。使用C++列出目錄中的文件,而不是遞歸,僅文件和子目錄

程序

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

using namespace boost::filesystem; 

int main(int argc, char *argv[]) 
{ 
    path const p(argc>1? argv[1] : "."); 

    auto list = [=] { return boost::make_iterator_range(directory_iterator(p), {}); }; 

    // Save entries of 'list' in the vector of strings 'names'. 
    std::vector<std::string> names; 
    for(auto& entry : list()) 
    { 
     names.push_back(entry.path().string()); 
    } 

    // Print the entries of the vector of strings 'names'. 
    for (unsigned int indexNames=0;indexNames<names.size();indexNames++) 
    { 
     std::cout<<names[indexNames]<<"\n"; 
    } 
} 

列出一個目錄下的文件,不是遞歸的,而且還列出了子目錄的名稱。我只想列出文件而不是子目錄。

如何更改代碼以實現此目的?

回答

4

列出目錄中的文件,而不是遞歸的,但也列出了子目錄的 名稱。我只想列出這些文件而不是 子目錄。

您可以使用boost::filesystem::is_directory過濾掉的目錄和只添加的文件:

std::vector<std::string> names; 
for(auto& entry : list()) 
{ 
    if(!is_directory(entry.path())) 
     names.push_back(entry.path().string()); 
} 
+0

是否接受'directory_entry'作爲參數?根據[文檔](http://www.boost.org/doc/libs/1_46_0/libs/filesystem/v3/doc/reference.html#is_regular_file),它將接受'file_status'或'path '。 –

+1

'is_regular_file'會跳過其他內容(例如鏈接)。有一個'is_directory'函數可能更合適。也許'is_directory(entry.path())'? –

+0

@BenjaminLindley,我的錯。更正 – WhiZTiM

相關問題