Richard
Richard

Reputation: 8758

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++?

I don't want to rely on system calls.

Upvotes: 2

Views: 4749

Answers (1)

Richard
Richard

Reputation: 8758

Example to grant 0777 to all files and folders in a directory using C++17 and its std::filesystem:

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 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

Related Questions