【问题标题】:List files in a directory, not recursive, only files and no subdirectories, using C++使用 C++ 列出目录中的文件,不递归,只有文件,没有子目录
【发布时间】:2017-03-03 14:44:03
【问题描述】:

这是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";
    }
}

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

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

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

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

    您可以使用boost::filesystem::is_directory 过滤掉目录并仅添加文件:

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

    【讨论】:

    • 它是否接受directory_entry 作为参数?根据the docs,它将接受file_statuspath
    • is_regular_file 将跳过其他内容(例如链接)。有一个is_directory 函数可能更合适。也许is_directory(entry.path())
    • @BenjaminLindley,我的错。已更正
    • @BorisGlick,你是对的。 is_directory 更适合这个。谢谢
    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2016-07-11
    • 2021-01-05
    • 2021-06-05
    • 1970-01-01
    • 2016-03-19
    相关资源
    最近更新 更多