You can remove the file as soon as you've created it, but it will persist as a real file system inode until you close the file.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/types.h>
static void exit_with_msg(const char *restrict msg);
static void pause_with_message(const char *restrict msg, ...);
int main(void) {
pid_t me = getpid();
printf("My PID=%d\n", (int)me);
char template[] = "/tmp/progXXXXXX";
int fd;
if ((fd = mkstemp(template)) == -1) {
exit_with_msg("Couldn't create temporary file\n");
}
pause_with_message("ls -l /tmp/prog* ; lsof -p %d",me);
(void) unlink(template);
// Now you will see something like
// /tmp/progCcuE5C (deleted)
// and file not found in the directory
pause_with_message("ls -l /tmp/prog* ; lsof -p %d",me);
char m1[] = "hello world\n";
write(fd,m1,strlen(m1));
off_t p1 = lseek(fd, 0, SEEK_CUR);
printf("Written %d so far\n", (int)p1);
// go back a bit
off_t p2 = lseek(fd, -6, SEEK_CUR);
printf("Step back Pos=%d\n", (int)p2);
char world[6] = { 0 };
read(fd,world,5);
off_t p3 = lseek(fd, 0, SEEK_CUR);
printf("Read <<%s>>, final pos=%d\n", world, (int)p3);
pause_with_message("lsof -p %d",me);
(void) close(fd);
// As soon as the fd is closed, it's gone for good.
pause_with_message("lsof -p %d",me);
return 0;
}
static void exit_with_msg(const char *restrict msg) {
fputs(msg, stderr);
exit(1);
}
static void pause_with_message(const char *restrict msg, ...) {
char cmd[100];
va_list ap;
va_start(ap,msg);
vsnprintf(cmd, sizeof(cmd), msg, ap);
printf(">>> %s\n",cmd);
system(cmd);
printf("Press enter to continue > ");
getchar();
va_end(ap);
}