5

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.

Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
Michael
  • 9,060
  • 14
  • 61
  • 123
  • 2
    `mkstemp` returns the name; it will modify the passed-in template argument (which is a char *, not a const char *) replacing the X's with the actual values. – Joe Dec 11 '12 at 18:37

1 Answers1

5

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.

piokuc
  • 25,594
  • 11
  • 72
  • 102
  • Ah, right you are. Not sure how I missed that reading the man page. Thanks! – Michael Dec 11 '12 at 18:39
  • Noticing that if I pass a string assigned like you did above I get a segfault in __gen_tempname. If I strdup it, then I don't. This may be platform dependant, but I would guess that in some cases string constants are being put in a read-only segment. – Michael Dec 11 '12 at 18:43
  • 1
    @Michael I believe the code is OK. Notice, that I didn't declare `fn` as a pointer to `char`. It is actually a local array (it's on the stack) initialized with the string literal data. – piokuc Dec 11 '12 at 18:51