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

List files in a directory, not recursive, only files and no subdirectories, using C++

本文关键字:文件 递归 子目录 使用      更新时间:2023-10-16

这是一个后续问题,用于提升目录示例 - 如何列出目录文件不递归。

程序

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

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

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

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

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

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