Creating Files#
O_CREAT And O_EXCL#
O_CREAT, combined withO_WRONLYor any other such flag [1], creates a file if it does not existIf the file is created, then
modeis used to initialize its permission maskAdditionally, if
flagscontainsO_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 (O_CREAT)#
Note:
modeis0666This is the preferred
modethat the program should specifyThe user’s Default Permissions: umask specifies the bits that are subtracted from it
Use this on
/tmp/somefilefrom previous section (Writing Files)⟶ File opened for overwrite (we did not say
O_APPEND)⟶ File mode as before (file existed)
Remove file, and call again
⟶ Created with
modespecified, butumasksubtracted (see here for an explanation ofumask)
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int fd = open("/tmp/somefile", O_WRONLY | O_CREAT,
0666); // <-- 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_EXCL)#
O_CREAT | O_EXCL: “exclusive” creationO_CREATcreates a file if it does not existO_EXCLfails if the file already exists⟶ No data can be accidentally overwritten
Prevents 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
modewhen 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:
modeshould be0666(rw-rw-rw-)Bits are subtracted from it using the user’s
umask(see here)
(Short demo maybe)