[英]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授予目录中的所有文件和文件夹的示例:
std::filesystem::recursive_directory_iterator()
to iterate through the directory std::filesystem::recursive_directory_iterator()
遍历目录 std::filesystem::permissions
to set the permissions for each file std::filesystem::permissions
设置每个文件的权限 std::filesystem::perms
to decide, which permissions should be set std::filesystem::perms
来决定,应该设置哪些权限 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_options
, fs::perm_options
包括add
和remove
fs::perms::add_perms
和fs::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.