cstringrandomloadrunnervugen

Vugen - create dynamic value in a mkdir path


I'm attempting to create a dynamic value within a string. In the below code line: char new_dir[] = "c:\\xyz";

I'd like to create a random number and use a parameter to replace xyz, this will allow random folder creation.

Any help is appreciated!

char filename[1024], command[1024];
char new_dir[] = "C:\\xyz";

if (mkdir(new_dir))
    lr_output_message ("Create directory %s failed", new_dir);
else
    lr_output_message ("Created new directory %s", new_dir);

sprintf(filename, "%s\\%s", new_dir, "newfile.txt");
sprintf(command, "dir /b c:\\ > %s /w", filename);
system(command);
lr_output_message ("Created new file %s", filename);

Solution

  • srand() seeds the random number generator with the time, otherwise the sequence is always the same. In Visual C the random numbers generated are in the range 0 to 32767. If that does not make a long enough dir name, do it twice, as in my example. I have padded out the filenames with zeroes.

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
        char new_dir[64];
        srand ((unsigned int)time(NULL));
    
        sprintf (new_dir, "C:\\%05d", rand());
        printf("Short dir name is %s\n", new_dir);
    
        sprintf (new_dir, "C:\\%05d%05d", rand(), rand());
        printf("Longer dir name is %s\n", new_dir);
    
        return 0;
    }