Creating Files#
O_CREAT
And O_EXCL
#
O_CREAT
, combined withO_WRONLY
or any other such flag [1], creates a file if it does not existIf the file is created, then
mode
is used to initialize its permission maskAdditionally, if
flags
containsO_EXCL
,open()
fails if the file exists⟶ Important when no two processes must create the same file and overwrite each other’s contents
Creating A File If It Does Not Exist#
Note:
mode
is0600
Use this on
/tmp/somefile
from previous section (Output To Files (write()))⟶ File opened for overwrite (we did not say
O_APPEND
)⟶ File mode as before (file existed)
Remove file, and call again
⟶ Created with
mode
specified
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int fd = open("/tmp/somefile", O_WRONLY | O_CREAT,
0600); // <-- note "mode"!
if (fd == -1) {
perror("open");
return 1;
}
// ... do something with fd ...
close(fd);
return 0;
}
Creating A File, Failing If It Already Exists#
O_CREAT | O_EXCL
: “exclusive” creationPrevents race condition if two processes …
see that a file does not exist
create it
if ("/tmp/somefile" does not exist) // <-- both see this
create "tmp/somefile"; // <-- both do this
Footnotes
Attention: mode
(A.k.a. Permissions)#
See also
Always specifiy
mode
when usingO_CREAT
: the new file needs well-defined permissions!C cannot tell you that it’s missing
⟶ Unspecified third parameter is the same as using uninitialized memory
Recommendation:
mode
should be0666
(rw-rw-rw-
)Bits are subtracted from it using the user’s
umask
(see here)
(Short demo maybe)