是否有一种跨平台的方法可以递归地设置C++中文件夹内容的权限?
我不想依赖系统呼叫。
发布于 2017-10-19 17:16:09
使用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,那么这还不是跨平台的。experimental/filesystem of VS17并不知道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.https://stackoverflow.com/questions/46835440
复制相似问题