2017-03-03 14 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'を受け入れていますか? [the docs](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

関連する問題