【问题标题】:C++ How to use std::filesystem::directory_optionsC++ 如何使用 std::filesystem::directory_options
【发布时间】:2020-02-07 02:29:58
【问题描述】:

这里的总菜鸟,所以如果这在其他地方被覆盖,请提前道歉,但是,我在谷歌的任何地方或任何其他地方都找不到合适的例子。

我正在使用 std::filesystem::recursive_directory_iterator 遍历目录树。当我到达一个我没有权限的目录时,它会引发异常。我知道 std::filesystem::directory_options 是我想要的,能够跳过权限被拒绝而不遵循符号链接;但我不确定如何使用它。

基本上我需要遍历目录树(可能非常非常大);跳过任何权限被拒绝的目录并且不遵循符号链接。如果每个目录都有任何类型的文件,则该目录将被添加到队列中以供以后使用。

代码片段如下。

谢谢。

for (auto& dirent : std::filesystem::recursive_directory_iterator(start_path))
{
    if (dirent.is_directory())
    {
        // CRASH if permission denied; need std::filesystem::options
        std::filesystem::path fsp = dirent.path();
        for (auto& subdirent : std::filesystem::directory_iterator(fsp))
        {
            if (!subdirent.is_directory())
            {
                dir_stack.push_back(dirent.path());
                break;
            }
        }
    }
}

【问题讨论】:

  • 参见构造函数 (4): en.cppreference.com/w/cpp/filesystem/… 和你需要的掩码元素。
  • 为什么要混合recursive_directory_iterator 和一个内部迭代器?看起来你可能会多次迭代同一个元素。

标签: c++ directory filesystems std options


【解决方案1】:

感谢你们为我指明了正确的方向。更多的挖掘和大量的试验和错误,我明白了。我希望这段代码是正确的,它做我想要的!是的,我知道我可以做一些速记的事情来缩短语句,但我的记忆力不是那么好 :) 再次感谢!

const std::filesystem::directory_options options = (
    std::filesystem::directory_options::follow_directory_symlink |
    std::filesystem::directory_options::skip_permission_denied
);

    try
    {
        for (const auto& dirent :
            std::filesystem::recursive_directory_iterator(start_path,
            std::filesystem::directory_options(options)))
        {
            …
        }
    catch(std::filesystem::filesystem_error &fse)
    {
        std::cout << "Caught fatal exception: "
            << std::endl
            << fse.what()
            << std::endl;
    }

【讨论】:

  • 您能解释一下| 运算符的用法吗??
  • 很简单。 std::filesystem::directory_options 定义为enum,通常由普通整数组成。 | 的使用是将follow_directory_symlink(即1)和skip_permission_denied (即2)的值做成一个bitwise OR。在内部,实现只需执行bitwise AND 来确定存在哪些标志。如需进一步参考,请参阅stackoverflow.com/questions/47981/…
【解决方案2】:

我已经编辑了代码:

   for (auto& dirent : std::filesystem::recursive_directory_iterator(start_path))
{
    if (dirent.is_directory())
    {
        // CRASH if permission denied; need std::filesystem::options
        std::filesystem::path fsp = dirent.path();
        for (auto& subdirent : std::filesystem::directory_iterator(fsp))
        {
            if (!subdirent.is_directory()&& !is_symlink(subdirent) && (fs::status(subdirent).permissions() ==  fs::perms::owner_all | fs::perms::group_all))
            {
                dir_stack.push_back(dirent.path());
                break;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 2019-04-11
    • 2020-11-04
    • 2020-09-27
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多