Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open a temporary file AND get its filename?

Tags:

c

file

posix

temp

I need to create a temporary file in my C program, write some data to it, and then invoke an external command (via exec or system) to do some processing on the file I just created. I did not write the external command nor is it feasible to integrate it into my program so I don't think I can share an already open descriptor with it. Therefore, I need to know the name of the temp file created.

The tempname() function does this, but unfortunately it recommends that you don't use itself, due to a possible race condition between getting the name and opening the file, and neither of the functions it recommends (tmpfile and mkstemp) provide a way to find out the actual name of the file created.

like image 763
Michael Avatar asked Dec 11 '12 18:12

Michael


1 Answers

It is not true that mkstemp does not let you know the temporary file name, try to compile and execute this program to see yourself:

#include <stdlib.h>
#include <stdio.h>

int main()
{   
    char fn[] = "/tmp/fileXXXXXX";
    int fd = mkstemp(fn);
    char cmd[200];
    int n = snprintf(cmd, sizeof(cmd), "ls -l %s\n", fn);

    printf("snprintf=>%d\n sizeof(fn)=%d\n", n, sizeof(fn)); // extra info, see comments

    printf("%s\n", cmd);
    return system(cmd);
} 

mkstemp will replace the file name template in the buffer you pass to it with actual file name, you can do whatever you want with this buffer later on.

like image 98
piokuc Avatar answered Sep 28 '22 06:09

piokuc