我正在使用boost迭代器"recursive_directory_iterator"来递归扫描目录.但是,当迭代器运行到我的应用程序无法访问的目录时,抛出类型"boost :: filesystem3 :: filesystem_error"的异常,这会停止迭代器并且程序将中止.无论如何,我可以指示迭代器跳过这些目录.
我尝试使用boost :: filesystem遍历目录时建议的代码而不抛出异常 但是,它确实对我没用.我正在使用boost版本1.49.
遵循建议(我能想出的最好的)之后我的代码如下:
void scand()
{
boost::system::error_code ec, no_err;
// Read dir contents recurs
for (recursive_directory_iterator end, _path("/tmp", ec);
_path != end; _path.increment(ec)) {
if (ec != no_err) {
_path.pop();
continue;
}
cout << _path->path() << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
艾哈迈德,谢谢你.
这是boost :: filesystem(V3)中的已知错误:https://svn.boost.org/trac/boost/ticket/4494.根据您的需要,您可以使用库的V2(它甚至可能以您的编译器的形式出现std::tr2::filesystem
).另一种选择是自己实现递归部分.
boost::system::error_code ec;
std::deque<boost::filesystem::path> directories {initialDir};
while(!directories.empty())
{
boost::filesystem::directory_iterator dit(directories.front(), ec);
directories.pop_front();
while(dit != boost::filesystem::directory_iterator())
{
if(boost::filesystem::is_directory(dit->path(), ec))
{
directories.push_back(dit->path());
}
HandleFile(dit->path()); // <-- do something with the file
++dit;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码只是为了给出一个大致的想法,缺少其他东西的错误检查.
您可以使用 try-catch 块,如果捕获 boost::filesystem3::filesystem_error 那么您可以跳过当前迭代:
void scand()
{
boost::system::error_code ec, no_err;
// Read dir contents recurs
recursive_directory_iterator end;
_path("/tmp", ec);
while (_path != end) {
try
{
if (ec != no_err) {
_path.pop();
continue;
}
cout << _path->path() << endl;
}
catch(boost::filesystem3::filesystem_error e)
{
}
_path++;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3413 次 |
最近记录: |