I'd like to create a unique temporary directory in Windows from some C code (not C++ or C#). I want to do this so that I can put some temp files in the directory, and then delete them all easily when I'm done (by removing the directory recursively).
I'm essentially looking for an equivalent of the linux
mkdtemp
function. There is a C# answer here, and responses on this
question
suggest using Boost. But since I'm using C, those solutions don't work
for me.
The best I've been able to come up with so far is to use
GetTempFileName
followed by CreateDirectory
,
but the problem there is that if I ask
GetTempFileName
to create a unique file name, it will also create the file (which I
don't want, since I want to make a directory instead).
Relatedly, there's
GetTempPath
,
which returns the location of the user's temp folder from environment
variables - but since I want to create my own directory that I can
safely delete later, I still need to create a directory inside any
path it would return.
It looks like if I want a unique directory to be created, I'll have to create a temp file, get the name, delete it, and then create a directory with the same name - which sounds very messy. Any other ideas?
Use GetTempPath
then CreateDirectory
with a random name under it, optionally retrying if CreateDirectory
fails due to it already existing. But if your name generation is good enough, the likelihood of a collision with an existing name is much smaller than the likelihood of a blackhat guessing your password or even your private key, so you might as well ignore it.
Use _tempnam
tmpnam_s
to create a filename that doesn't exist yet, and then use CreateDirectory
to create the directory. There's technically a race condition if you do this, in that another process could potentially create a file or directory with that name in the time in between when you generate the filename and when you create the directory, but the odds of that are rather unlikely. To protect against that, you can loop until you succeed.
For recursively removing a directory tree, you can use SHFileOperation
. Alternatively, you can do the directory traversal yourself with FindFirstFile
/FindNextFile
, DeleteFile
, and RemoveDirectory
.
If you want to remove the directory automatically upon exiting, register a function using atexit
. This will only work for normal program termination (i.e. via the exit
function or via returning from main
/WinMain
). This will not work for abnormal program termination (e.g. via abort
, an access violation, someone else calling TerminateProcess
, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With