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.
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.
#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;
}mode 0644That 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.