I could use int open(const char *pathname, int flags, mode_t mode); and thus control the file permissions (represented by mode_t)
Not really. Unless you set your process's umask
setting. Because the permissions passed to open()
are not the permissions the created file is necessarily created with.
Per POSIX open()
(bolding mine):
the access permission bits (see <sys/stat.h>
) of the file mode shall be set to the value of the argument following the oflag
argument taken as type mode_t
modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared.
So
int fd = open( someFileName, O_CREAT | O_RDWR, 0644 );
is NOT guaranteed to set the file permissions to 0644
.
If your file creation mask is set to 0077
, then the file will actually be created with permissions set to 0600
.
Note that the umask()
setting is a process-wide property, and it's not really a good idea to change it much. And if you're trying to write general-purpose code that has no side effects, it's a bad idea to change it at all. For example, changing the umask()
setting in a multithreaded process in order to allow wider access to files being created can cause
security problems if another thread creates a file at the same time.
The best way to set file permissions to be exactly what you want is to set file permissions to be exactly what you want with fchmod()
:
FILE *f = fopen(...);
fchmod( fileno( f ), 0644 );
In fact, since the umask()
setting is a process-wide property, it's always possible in general that it can be changed by another thread at any time, so setting the permissions explicitly via chmod()
or fchmod()
is the only guaranteed way to get exactly the permissions specified in all circumstances.