Creating Files#

O_CREAT And O_EXCL#

  • O_CREAT, combined with O_WRONLY or any other such flag [1], creates a file if it does not exist

  • If the file is created, then mode is used to initialize its permission mask

  • Additionally, if flags contains O_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 is 0600

  • 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” creation

  • 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)#

  • Always specifiy mode when using O_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 be 0666 (rw-rw-rw-)

    • Bits are subtracted from it using the user’s umask (see here)

(Short demo maybe)