I am writing a C++ program which needs to create a temporary file for its internal usage. I would like to allow concurrent executions of the program by running multiple processes, so the temporary file name needs to be randomized, that way each spawned process will generate a unique temporary file name for its own use.
I am using rand() to generate random characters for part of the file name, so i need to initialize the random number generator’s seed using srand().
What options are there for passing a good argument to srand() such that two processes will not be initialized with the same seed value?
My code needs to work both on Windows and on Linux.
The question is actually asking how to create a uniquely-named temporary file.
The operating system probably provides an API for this, which means you do not have to generate your own name.
On Windows, its called
GetTempFileName()andGetTempPath().On Unix, use
tmpfile().(Windows supports
tmpfile()too; however, I’ve heard reports that from others that, whilst it works nicely on XP, it fails on Vista if you’re on the C: drive and you are not an administrator; best to use theGetTempFileName()method with a custom, safe path)