Filtering folders in Boost Filesystem

為{幸葍}努か 提交于 2021-01-28 04:06:55

问题


I want to get all the files inside a concrete folder (in this case Documents) with Boost Filesystem in Windows.

For this I make a filter to assure I get no folders.

The problem is that when I still get the following folders :

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

(I don't get some other folders)

The code is the following:

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

Is there any way to avoid this folders without making a manual filtering?

Thanks a lot!


回答1:


These are likely junctions.

I just tried it on a windows box by using junction.exe (from sysinternals) to make a junction point, and using this little test program to pinpoint them:

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

Now running this with test.exe "C:\WORK" printed

"C:\WORK\MyJunction"

Note that the assers prove that is neither a regular file nor a directory.


In slightly unrelated news, this is rather sweet for directory iteration:

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

Using these rather simple helpers:

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);
}

See it Live on Coliru



来源:https://stackoverflow.com/questions/20547921/filtering-folders-in-boost-filesystem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!