Setting file permissions when opening a file with ofstream

xgord picture xgord · Nov 5, 2015 · Viewed 9.6k times · Source

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

Answer

Miles Budnek picture Miles Budnek · Nov 5, 2015

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().