Reputation: 8758
Is there a cross-platform way to recursively set permissions for the contents of a folder in C++?
I don't want to rely on system calls.
Upvotes: 2
Views: 4749
Reputation: 8758
Example to grant 0777 to all files and folders in a directory using C++17 and its std::filesystem
:
std::filesystem::recursive_directory_iterator()
to iterate
through the directorystd::filesystem::permissions
to set the permissions for each filestd::filesystem::perms
to decide, which permissions should be setCode:
#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 e.g. fs::perm_options::add
instead of fs::perm_options::replace
is desired, then this is not yet cross-platform. 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. This implies that the signature of std::filesystem::permissions
is slightly different:
Std:
fs::permissions(path, fs::perms::all, fs::perm_options::add);
VS17:
fs::permissions(path, fs::perms::add_perms | fs::perms::all); // VS17.
Upvotes: 3