Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a directory with boost::filesystem without throwing exceptions

I have a path to the directory, and I want to traverse through all of its sub-directories, collecting files' pathes by the way.

namespace fs = boost::filesystem;

std::vector<fs::path> traverse_if_directory(fs::path& f) {
    std::vector<fs::path> result;
    if (fs::is_directory(f)) {      
        for (fs::recursive_directory_iterator it(f), eit; it != eit; ++it) {
            if (!fs::is_directory(it->path())) {
                result.push_back(it->path());
            }       
        }
    }
    else {
        result.push_back(f);
    }

    return result;
}

Unfortunately, in the middle of the traversing, I stumble upon a directory which I have no rights to look at, and the code above throws. But obviously, in this scenario it's not an exception, I should just go on, skipping this locked directory.

But how do I do this?

like image 918
Joker_vD Avatar asked Apr 12 '13 11:04

Joker_vD


1 Answers

Ha, figured it out, there is a way:

std::vector<fs::path> traverse_if_directory(fs::path& f) {
    std::vector<fs::path> result;
    boost::system::error_code ec;

    if (fs::is_directory(f)) {      
        for (
             fs::recursive_directory_iterator it(f, ec), eit;
             it != eit;
             it.increment(ec)
            ) {
            if (ec) {
                it.pop();
                continue;
            }
            if (!fs::is_directory(it->path())) {
                result.push_back(it->path());
            }
        }
    }
    else {
        result.push_back(f);
    }

    return result;
}

There is a non-throwing overload which accepts an output parameter of type boost::system::error_code, so I can just check after each increment if there were any error.

like image 197
Joker_vD Avatar answered Sep 26 '22 03:09

Joker_vD