I have a program that calls mkstemp(), writes some stuff with the fd returned and then closes the fd. I want the file to remain until I delete it myself! With something like rm command, or whatever. My question is: will Linux delete this file after close(fd)?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With