Can anybody point me to the code that implements mkstemp() (C/C++) on Win32, or very close analog.
Must be race-free.
It's supposed to look like
#include <windows.h>
#include <io.h>
// port of mkstemp() to win32. race-free.
// behaviour as described in http://linux.die.net/man/3/mkstemp
//
int mkstemp(char *template) {
...
}
Thanks
You can use the following function which is extracted from
wcecompat
library (from filesrc/stdlib_extras.cpp
)It defines
O_EXCL
as;You can rip out mkstemp support out of it easily.
Actually, using _mktemp_s() is a really bad idea -- only 26 possible file name candidates in any one context, and, with this limited range to be attacked, it exposes the very race condition that mkstemp() is designed to overcome. However, the other proposed solution, while much better, is also flawed, insofar as it attributes 62 degrees of freedom in the choice of substitute file name characters, whereas the case insensitivity of the Windows file system consumes 26 of these, thus leaving only 36; this has the effect of weighting the probability of selecting any logically distinguishable alphabetic character at double that for a numeric.
With this in mind, I've posted a MinGW patch here: https://sourceforge.net/p/mingw/bugs/2003/
If adopted, this will formally add both mkstemp() and mkdtemp() to the standard MinGW distribution.
You can use _mktemp_s() function, or any of it's variations:
where:
_mktemp_s
; wide characters in_wmktemp_s
, including the null terminator.It returns 0 on success, and an error code on failure. Note that the function modifyes the
template
argument.