Reputation: 12178
I have a tool that needs to create a unique directory each time it is launched.
This tool can be launched multiple times at the same second
When I use the regular srand(time(NULL))
and rand()
, I get the same "unique" string if my tool was launched more than once at the same second.
Here is an example for my problem:
$ ./rand_string.exe
9IQMT8F63P37G3LO4O85LM1LRTEBTV3Q1DOX3B46SAUYUBPYKDMZER9M8DAZSVPT
$ ./rand_string.exe
I01QZ47I0FV3WCW597NLE3M9B75Q5S5ADFB23T4OZR0W2VM2E91XJYHWGGVMEAE0
# Time is still the same, getting same "unique" string
$ ./rand_string.exe
I01QZ47I0FV3WCW597NLE3M9B75Q5S5ADFB23T4OZR0W2VM2E91XJYHWGGVMEAE0
# Time is still the same, getting same "unique" string
$ ./rand_string.exe
I01QZ47I0FV3WCW597NLE3M9B75Q5S5ADFB23T4OZR0W2VM2E91XJYHWGGVMEAE0
$ ./rand_string.exe
LWNXWSTODGGC8B46JB0ZII950LJOPJ8EG3GEI885U58CLXHA3L0DBCXIX6I0I2SZ
$ ./rand_string.exe
UUY1245J9RO8O1G6OVEYBZUTK0PNGG9ER52JIQSN1MEUDGZEXHFBHJ6R6TJ74H1Q
$ ./rand_string.exe
3SP49GYF6HG4KAS7UVTELWWG4FW28UAY384PI8CLP3ZS50WIRXFTMQEKEWKE6DQY
# Time is still the same, getting same "unique" string
$ ./rand_string.exe
3SP49GYF6HG4KAS7UVTELWWG4FW28UAY384PI8CLP3ZS50WIRXFTMQEKEWKE6DQY
Here is my code (just to make sense for the "random" implementation):
#include <cstdlib>
#include <ctime>
#include <iostream>
void cpy_rand_str(char *dest, int size) {
int i;
int rand_num;
srand (time(NULL));
for (i = 0 ; i < size ; i++) {
rand_num = rand() % 36;
if (rand_num >= 10) {
rand_num += ('A' - 10);
} else {
rand_num += '0';
}
dest[i] = (char)rand_num;
}
dest[size] = '\0';
}
int main() {
char my_key[64 + 1];
cpy_rand_str(my_key, 64);
std::cout << my_key << "\n";
return 0;
}
Upvotes: 1
Views: 2435
Reputation: 2984
You could use actual UUIDs with boost for example:
boost::uuids::basic_random_generator<boost::mt19937> gen;
boost::uuids::uuid u = gen(); //generate uuid
std::string s1 = to_string(u);
Which will be platform independent and have a very low probability for collision.
Upvotes: 2
Reputation: 490098
This is pretty much what tmpnam
was designed to accomplish. It's not perfect (e.g., it's open to race conditions) but stands at least some chance of working, which is more than you can say for most of the obvious alternatives. As a bonus, the string it generates is specifically intended to conform to the host's requirements as a file name, which usually means it's usable as the name of a directory.
Upvotes: 2