When a file created with mkstemp() is deleted?

will Linux delete this file after close(fd)?

Not automatically. You need to call unlink on the file manually. You can do this immediately after calling mkstemp if you don’t need to access the file by name (i.e. via the file system) — it will then be deleted once the descriptor is closed.

Alternatively, if you need to pass the file on to another part of the code (or process) by name, don’t call unlink just yet.

Here’s an example workflow:

char filename[] = "tempfile-XXXXXX";
int fd;
if ((fd = mkstemp(filename)) == -1) {
    fprintf(stderr, "Failed with error %s\n", strerror(errno));
    return -1;
}

unlink(filename);

FILE *fh = fdopen(fd, "w");
fprintf(fh, "It worked!\n");
fclose(fh);

fclose closes the FILE* stream, but also the underlying file descriptor, so we don’t need to explicitly call close(fd).

Necessary headers:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>