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;
}