You have to use the open(2) syscall with O_EXCL|O_CREAT|O_WRONLY
and then call fdopen(3) on that descriptor.
#include <sys/errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *program = argv[0];
char *filename = argv[1];
if (argc != 2) {
fprintf(stderr, "%s: expected a single file argument.\n", program);
exit(1);
}
int flags = O_EXCL|O_CREAT|O_WRONLY;
int mode = 0666;
int fd;
if ((fd = open(filename, flags, mode)) == -1) {
fprintf(stderr, "%s: cannot open %s with flags 0x%04X: %s\n",
program, filename, flags, strerror(errno));
exit(2);
}
FILE *fp = fdopen(fd, "w");
if (fp == NULL) {
fprintf(stderr, "%s: cannot fdopen file descriptor %d: %s\n",
program, fd, strerror(errno));
exit(3);
}
if (fprintf(fp, "12345\n") == EOF) {
fprintf(stderr, "%s: cannot write to %s: %s\n",
program, filename, strerror(errno));
exit(4);
}
if (fclose(fp) == EOF) {
fprintf(stderr, "%s: cannot close %s: %s\n",
program, filename, strerror(errno));
exit(5);
}
exit(0);
}
Those open(2) flags are amongst the few guaranteed by POSIX.
This is not guaranteed to work reliably on remote filesystems. In particular, NFS breaks the POSIX rules about atomic creats. [sic]