如何使用Boost Filesystem忽略隐藏文件(和隐藏目录中的文件)?
问题描述:
我使用以下内容递归遍历目录中的所有文件:
I am iterating through all files in a directory recursively using the following:
try
{
for ( bf::recursive_directory_iterator end, dir("./");
dir != end; ++dir )
{
const bf::path &p = dir->path();
if(bf::is_regular_file(p))
{
std::cout << "File found: " << p.string() << std::endl;
}
}
} catch (const bf::filesystem_error& ex) {
std::cerr << ex.what() << '\n';
}
但这包括隐藏文件和隐藏目录中的文件。
But this includes hidden files and files in hidden directories.
如何过滤掉这些文件?
How do I filter out these files? If needed I can limit myself to platforms where hidden files and directories begin with the '.' character.
答
不幸的是,没有什么可以隐藏的文件和目录以'。'字符开头。 t似乎是一种跨平台处理隐藏的方式。以下适用于类似Unix的平台:
Unfortunately there doesn't seem to be a cross-platform way of handling "hidden". The following works on Unix-like platforms:
首先定义:
bool isHidden(const bf::path &p)
{
bf::path::string_type name = p.filename();
if(name != ".." &&
name != "." &&
name[0] == '.')
{
return true;
}
return false;
}
然后遍历文件变成:
try
{
for ( bf::recursive_directory_iterator end, dir("./");
dir != end; ++dir)
{
const bf::path &p = dir->path();
//Hidden directory, don't recurse into it
if(bf::is_directory(p) && isHidden(p))
{
dir.no_push();
continue;
}
if(bf::is_regular_file(p) && !isHidden(p))
{
std::cout << "File found: " << p.string() << std::endl;
}
}
} catch (const bf::filesystem_error& ex) {
std::cerr << ex.what() << '\n';
}