4

I'm working with some legacy code which passes around the name of a file. I'd like to create a temp file and give the legacy code the name of the file to be opened later using legacy functions. tmpnam is unsafe due to the race case between getting the name and creating the file. mkdir isn't portable to Windows and doesn't let me have the name of the file. How can I create a temp file safely, portably, and with retention of file name?

SonicN
  • 163
  • 7
  • 1
    Define your portability requirements. The standard C library has nothing to offer. If you need portability between Windows and non-Windows, you're going to need to define a portable interface to non-portable implementations of the function(s) — what you do on Windows will be different in detail from what you do on Unix. I'm not clear the `mkdir()` is necessary; you can simply demand that the directory be already created. – Jonathan Leffler Aug 01 '17 at 20:13
  • I wrote a Unix-based set of functions: `extern void tfn_setdirectory(const char *dir); extern void tfn_setprefix(const char *pfx); extern int tfn_tempfilename(const char *sfx, char *buffer, size_t bufsiz); extern int tfn_tempdirname(const char *sfx, char *buffer, size_t bufsiz);` to cover a portability problem between different variants of Unix. It could be used as a basis for a Windows and Unix variant. It uses two 32-bit random numbers as part of the name — and you can control the directory and file suffix. It uses a sequence of environment variables to find the default directory. – Jonathan Leffler Aug 01 '17 at 20:17
  • Shout if you would like the code — either by comment `@Jonathan` or see my profile. – Jonathan Leffler Aug 01 '17 at 20:18

1 Answers1

0

In windows GetTempFileName function. In Linux if you do not more than 25 files (bug in some implementations) mkstemp family of functions or tmpfile

melpomene
  • 84,125
  • 8
  • 85
  • 148
0___________
  • 60,014
  • 4
  • 34
  • 74