是否有跨平台方式以C ++方式递归设置文件夹内容的权限?
我不想依赖系统调用。
答案 0 :(得分:1)
使用C ++ 17及其std::filesystem
向目录中的所有文件和文件夹授予0777的示例:
std::filesystem::recursive_directory_iterator()
进行迭代
通过目录std::filesystem::permissions
设置每个文件的权限std::filesystem::perms
决定应设置哪些权限代码:
#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
,而是将add
和remove
包括为fs::perms::add_perms
和fs::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.