为C ++中的文件夹中的所有文件设置权限

时间:2017-10-19 17:16:10

标签: c++ cross-platform

是否有跨平台方式以C ++方式递归设置文件夹内容的权限?

我不想依赖系统调用。

1 个答案:

答案 0 :(得分:1)

使用C ++ 17及其std::filesystem向目录中的所有文件和文件夹授予0777的示例:

代码:

#include <exception>
//#include <filesystem>
#include <experimental/filesystem> // Use this for most compilers as of yet.

//namespace fs = std::filesystem;
namespace fs = std::experimental::filesystem; // Use this for most compilers as of yet.

int main()
{
    fs::path directory = "change/permission/of/descendants";
    for (auto& path : fs::recursive_directory_iterator(directory))
    {
        try {
            fs::permissions(path, fs::perms::all); // Uses fs::perm_options::replace.
        }
        catch (std::exception& e) {
            // Handle exception or use another overload of fs::permissions() 
            // with std::error_code.
        }           
    }
}

如果是需要fs::perm_options::add而不是fs::perm_options::replace,那么这还不是跨平台的。 VS17的experimental/filesystem并不知道fs::perm_options,而是将addremove包括为fs::perms::add_permsfs::perms::remove_perms。这意味着std::filesystem::permissions的签名略有不同:

标准

fs::permissions(path, fs::perms::all, fs::perm_options::add);

VS17:

fs::permissions(path, fs::perms::add_perms | fs::perms::all); // VS17.
相关问题