本文介绍了使用boost :: filesystem遍历目录,而不抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个目录路径,我想遍历所有的子目录,收集文件的路径。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.但是我该怎么做呢?推荐答案哈,想出来,有一种方法: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;}有一个非throwing重载,接受一个 boost :: system :: error_code ,所以我可以检查每个增量之后如果有任何错误。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. 这篇关于使用boost :: filesystem遍历目录,而不抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-24 16:13
查看更多