简体   繁体   English

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

[英]Set permission for all files in a folder in C++

Is there a cross-platform way to recursively set permissions for the contents of a folder in C++? 是否有跨平台的方法来递归地设置C ++中文件夹内容的权限?

I don't want to rely on system calls. 我不想依靠系统调用。

Example to grant 0777 to all files and folders in a directory using C++17 and its std::filesystem : 使用C ++ 17及其std::filesystem将0777授予目录中的所有文件和文件夹的示例:

Code: 码:

#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.
        }           
    }
}

If eg fs::perm_options::add instead of fs::perm_options::replace is desired, then this is not yet cross-platform. 如果需要例如fs::perm_options::add而不是fs::perm_options::replace ,那么这还不是跨平台的。 experimental/filesystem of VS17 doesn't know fs::perm_options and includes add and remove as fs::perms::add_perms and fs::perms::remove_perms instead. VS17的experimental/filesystem不知道fs::perm_optionsfs::perm_options包括addremove fs::perms::add_permsfs::perms::remove_perms This implies that the signature of std::filesystem::permissions is slightly different: 这意味着std::filesystem::permissions的签名略有不同:

Std: 标准:

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

VS17: VS17:

fs::permissions(path, fs::perms::add_perms | fs::perms::all); // VS17.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM