使用C++列出目录中的文件,而不是递归,仅文件和子目录
问题描述:
这是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";
}
}
列出一个目录下的文件,不是递归的,而且还列出了子目录的名称。我只想列出文件而不是子目录。
如何更改代码以实现此目的?
答
列出目录中的文件,而不是递归的,但也列出了子目录的 名称。我只想列出这些文件而不是 子目录。
您可以使用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'作为参数?根据[文档](http://www.boost.org/doc/libs/1_46_0/libs/filesystem/v3/doc/reference.html#is_regular_file),它将接受'file_status'或'path '。 –
'is_regular_file'会跳过其他内容(例如链接)。有一个'is_directory'函数可能更合适。也许'is_directory(entry.path())'? –
@BenjaminLindley,我的错。更正 – WhiZTiM