Skip to content
systemcoding.dev
Systems Programming

Open a file for writing with O_CREAT, O_TRUNC and mode 0644

Open a file for writing with O_WRONLY, O_CREAT, O_TRUNC and mode 0644 on Linux 6.12. The mode is masked by umask, so the file may end up less open.

1 min read
Summarize in AI

The usual way to write a fresh file with the system call interface is open with three flags and a mode: O_WRONLY to write, O_CREAT to create it if it is missing, and O_TRUNC to throw away any existing contents. The mode argument is only read when O_CREAT is present, and it sets the permission bits of a newly created file. The flags are defined in POSIX open.

create.cc
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void) {
    int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) {
        perror("open");
        return 1;
    }
    struct stat st;
    fstat(fd, &st);
    printf("mode %04o\n", st.st_mode & 07777);
    close(fd);
    return 0;
}
Text
mode 0644

That is the result with the common umask of 022. The kernel creates the file with mode & ~umask, so under 077 the same call yields 0600, and no error tells you the bits were reduced. If a file must have exact permissions, follow the open with fchmod, which umask does not touch.

The mode is ignored when the file already exists, so 0644 here never changes an existing file's permissions. Skipping the third argument when you pass O_CREAT is undefined behaviour: the call reads an arbitrary value from the stack and may create a file with random permissions.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.