使用C ++列出目录中的文件,而不是递归文件,只列出文件和子目录

时间:2017-03-03 14:44:04

标签: c++ boost

这是boost directory_iterator example - how to list directory files not recursive的后续问题。

该计划

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

列出目录中的文件,而不是递归文件,但也列出了子目录的名称。我只想列出文件而不是子目录。

如何更改代码才能实现此目的?

1 个答案:

答案 0 :(得分: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());
}