c++ - 过滤 Boost 文件系统中的文件夹

标签 c++ boost window boost-filesystem

我想使用 Windows 中的 Boost 文件系统获取具体文件夹(在本例中为文档)内的所有文件。

为此,我创建了一个过滤器以确保我没有得到任何文件夹。

问题是当我仍然得到以下文件夹时:

"C:\....\Documents\My Videos", 
"C:\....\Documents\My Music",
"C:\....\Documents\My Pictures"

(我没有得到其他一些文件夹)

代码如下:

boost::filesystem::directory_iterator end;
for (boost::filesystem::directory_iterator iter(documentsFolder); iter != end; ++iter){
    if (!is_directory(*iter)){
        std::cout << iter->path() << "\n";
    }
    else{
        std::cout << "-------->>>" << iter->path() << "\n";
    }

有什么方法可以在不进行手动过滤的情况下避开此文件夹吗?

非常感谢!

最佳答案

这些可能是交叉点。

我刚刚在 Windows 盒子上尝试了它,使用 junction.exe (来自 sysinternals)创建一个连接点,并使用这个小测试程序来精确定位它们:

#include <boost/range/iterator_range.hpp>
#include <boost/filesystem.hpp>
#include <vector>
#include <string>
#include <iostream>

int main(int argc, char* argv[])
{
    using namespace boost::filesystem;
    std::vector<std::string> args(argv+1, argv+argc);
    if (args.empty()) args.push_back("C:\\WORK");

    for (auto dir : args)
    {
        recursive_directory_iterator f(dir), l;
        for (directory_entry& entry : boost::make_iterator_range(f,l))
        {
            if (is_other(entry))
            {
                assert(!is_regular_file(entry));
                assert(!is_directory(entry));
                std::cout << entry << "\n";
            }
        }
    }
}

现在运行它并打印test.exe "C:\WORK"

"C:\WORK\MyJunction"

请注意,断言者证明它既不是常规文件也不是目录


在稍微不相关的新闻中,这对于目录迭代来说相当不错:

int main(int argc, char* argv[])
{
    using namespace boost::adaptors;

    std::vector<std::string> const args(argv+1, argv+argc);

    for (auto& dir : args)
        for (auto& entry : traverse_directory(dir) | filtered(is_valid_file))
            std::cout << entry << "\n";
}

使用这些相当简单的助手:

template <typename T>
boost::iterator_range<boost::filesystem::recursive_directory_iterator> traverse_directory(T const& dir) {
    boost::filesystem::recursive_directory_iterator f(dir), l;
    return boost::make_iterator_range(f, l);
}

static bool is_valid_file(boost::filesystem::directory_entry const& entry) {
    return is_regular_file(entry) && !is_other(entry);
}

查看 Live on Coliru

关于c++ - 过滤 Boost 文件系统中的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20547921/

相关文章:

c++ - 为什么我们将 "this"指针传递给 setupUi 函数?

C++/Boost 模板运行时多态性

c - winapi c - 添加图像的任何简单方法?

c++ - 使用 Cygwin boost asio 错误

javascript - 使用亚马逊付款 在弹出窗口中打开

JavaScript:获取动态生成的对象的值

c++ - 私有(private)类名缩写技巧?

c++ - 为什么这个 typedef 不起作用

c++ - LNK2019 : unresolved extrenal symbol when using std::ifstream

c++ - 编译文件的变体问题