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.
srand() uses its argument seed as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand(). If srand() is not called, the rand() seed is set as if srand(1) was called at program start.
Many researchers worry about how to choose a random number seed. Some people use an easy-to-remember sequence such as their phone number or the first few digits of pi. Others use long prime numbers such as 937162211.
The generation of the pseudo-random number depends on the seed. If you don't provide a different value as seed, you'll get the same random number on every invocation(s) of your application. That's why, the srand() is used to randomize the seed itself.
Note that we need to usually call the srand () function only once before the call to rand () function and not every time we generate random numbers. Return value: An integer value between 0 and RAND_MAX.
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()
and GetTempPath()
.
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 the GetTempFileName()
method with a custom, safe path)
If you are trully just needing a temp file you can use:
FILE* tmpfile(); // Generate an unnamed temporary file.
char* tmpnam(char* s); // Generate a file name in the director specified by TMPDIR
Use time:
srand(time(NULL));
Also note that rand() probably is not thread safe.
So be careful how you use it. Two threads entering rand at the same time are going to cause problems.
I've never used it myself, but you might be able to use tmpnam()
to generate your temporary file name. A quick search indicated support on both Windows and Linux.
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