Skip to content

Instantly share code, notes, and snippets.

Last active January 11, 2018 00:30
What would you like to do?
How to atomically write a file without giving it a temporary name
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
// Can't get O_TMPFILE to work for some reason.
#ifndef __O_TMPFILE
# define __O_TMPFILE (020000000 | __O_DIRECTORY)
int main() {
int fd = open(".", __O_TMPFILE | O_RDWR, 0600);
if (fd == -1) {
perror("open failed");
return 1;
if (12 != write(fd, "hello world\n", 12)) {
perror("write failed");
return 1;
char buf[800];
sprintf(buf, "/proc/self/fd/%d", fd);
if (-1 == linkat(AT_FDCWD, buf, AT_FDCWD, "helloworld.txt", AT_SYMLINK_FOLLOW)) {
perror("linkat failed");
return 1;
// note that linkat does not allow replacing existing files, so this is less
// useful than it seems :/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment