1

This is a follow up question to boost directory_iterator example - how to list directory files not recursive.

The program

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

lists the files in a directory, not recursive, but also lists the names of the subdirectories. I only want to list the files and not the subdirectories.

How do I change the code to achieve this?

Community
  • 1
  • 1
Adriaan
  • 715
  • 10
  • 22

1 Answers1

4

lists the files in a directory, not recursive, but also lists the names of the subdirectories. I only want to list the files and not subdirectories.

You may use boost::filesystem::is_directory to filter out directories and add only files:

std::vector<std::string> names;
for(auto& entry : list())
{
    if(!is_directory(entry.path()))
        names.push_back(entry.path().string());
}
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • Does it accept a `directory_entry` as an argument? According to [the docs](http://www.boost.org/doc/libs/1_46_0/libs/filesystem/v3/doc/reference.html#is_regular_file), it will accept either a `file_status` or a `path`. – Benjamin Lindley Mar 03 '17 at 14:51
  • 1
    `is_regular_file` will skip other things (for example, links). There's an `is_directory` function that might be more appropriate. Perhaps `is_directory(entry.path())`? – Boris Glick Mar 03 '17 at 14:53
  • @BenjaminLindley, my mistake. Corrected – WhiZTiM Mar 03 '17 at 14:54
  • @BorisGlick, you are right. `is_directory` is more suitable for this. Thanks – WhiZTiM Mar 03 '17 at 14:55