You can use boost::filesystem
to accomplish this with the following function:
void permissions(const path& p, perms prms);
a path
can be constructed from a string, so no problem there. The hard part is the perms
which is a sort of bit mask. You need to use remove_perms
in that bitmask to signal that permissions should be removed.
The following code should work (untested):
using boost::filesystem::perms;boost::filesystem::path myPath("foo.txt");boost::filesystem::permissions(myPath, perms::remove_perms|perms::owner_write|perms::others_write|perms::group_write);
Edit 9/8/2020
A note about deleting read-only files. In Linux, so long as someone has write-access to the immediate parent directory, they can remove the file (unless you take extreme measures). In Windows, you will need to restore write access to the file in order to delete it.
I chose to remove permissions instead of set the permissions explicitly to read-only in the original answer because the Boost docs have a note about how only the write permissions do anything. Anecdotally, I can say that I've had success with permissions(path, owner_read|others_read|group_read)
(In windows), but to be on the safe side we should follow the docs, I guess.
I'd also like to note that this entire answer is basically moot if you have C++17, because std::filesystem
is available to you (the API is very much like Boost's).