I'm writing a program that writes output to a file. If this file doesn't exist, I want to create it.
Currently, I'm using the following flags when calling open: O_WRONLY | O_CREATE
However, when this creates the file, it doesn't give me any permissions to write to it...
How can I use open so that it creates a file if it doesn't exist, but will create it with necessary permissions when needed?
Thanks!
From the manual:
So it seems you need to pass a third argument specifying the desired file permissions.
On Linux there's a third argument you can use to pass permissions. S_IWUSR should be the flag to give you write permissions, but in practice you'll probably want to use more flags than just that one (bitwise or'd together). Check the manpage for a list of the permission flags.
Note that under POSIX (Unix, Linux, MacOS, etc) you can open and create a file with any permissions you choose, including 0 (no permission for anyone), and yet still write to the file if opened for writing.
Just use the optional third argument to
open
:so like this:
See
man open(2)
.You probably need the third argument. For example: