Reputation: 4776
Is there a way in C++'s standard libraries (or linux sys/stat.h, sys/types.h, sys/.... libraries) to set the file permissions of a file when creating it with ofstream
(or using something else from those libraries)?
When I create a file it just gets created with some default set of file permissions (I assume whatever the current umask
is), but I want to explicitly set the permissions to something other than the default (ex. 600
), and I can't just set the umask before starting the program (b/c others will run it).
// Example of creating a file by writing to it
ofstream fp(filename.c_str())
/* write something to it */
Is there a way to do this in C++ or if not, a way to set the umask
within the C++ program?
For example, in C's standard library you can just do:
open(filename, O_RDWR|O_CREAT, 0666)
but I don't want to resort to using the C function, as it'd be nice to be able to use the functions associated with fstream
objects.
(Side Note: there was a question whose title was exactly what I was looking for, but it turned out to be unrelated.)
Upvotes: 9
Views: 20611
Reputation: 2714
In C++17, std::filesystem::permissions
was introduced. It will enable you to get and set permissions in a platform-agnostic manner.
Get permissions:
using fs = std::filesystem;
bool owner_can_read =
fs::status("my_file.txt").permissions() & fs::perms::owner_read != fs::perms::none;
Set permissions (add all permissions for owner and group, that is, add modes 0x770 on unix):
using fs = std::filesystem;
fs::permissions("my_file.txt",
fs::perms::owner_all | fs::perms::group_all,
fs::perm_options::add);
Example based on an example from cppreference.
Upvotes: 9
Reputation: 30569
You cannot. The standard library must be platform agnostic, and permissions like 0600
are meaningless on Windows for example. If you want to use platform-specific features, you'll need to use platform-specific APIs. Of course, you can always call umask()
before you open the file, but that's not part of the C++ standard library, it's part of the platform API.
Note: open()
isn't part of the C standard library either. It's a platform API. The C standard library function to open a file is fopen()
.
Upvotes: 8