0

This program should create 10 randomly named files with unicode string names on a desktop but it only creates just 1. I tried using delete[] statements at the end of the createfiles function to deallocate the memory for output, file and desktop but it still doesn't work. Am I doing something wrong?

#include "shlobj_core.h"
#include <fstream>
#include <iostream>
#include <Windows.h>

wchar_t* generateRandomUnicodeString(size_t len, size_t start, size_t end)
{
    wchar_t* ustr = new wchar_t[len + 1];
    size_t intervalLength = end - start + 1;

    srand(time(NULL));
    for (auto i = 0; i < len; i++) {
        ustr[i] = (rand() % intervalLength) + start;
    }
    ustr[len] = L'\0';
    return ustr;
}

void createfiles(int number)
{
    if (number == 0) {
        return;
    }
    wchar_t* output = generateRandomUnicodeString(5, 0x0400, 0x04FF);

    LPWSTR desktop;
    LPWSTR file;
    SHGetKnownFolderPath(FOLDERID_Desktop, 0, 0, &desktop);
    PathAllocCombine(desktop, output, 0, &file);

    std::wofstream ofs(file);
    ofs << "File Description";
    delete[] output;
    output = nullptr;
    delete[] file;
    file = nullptr;
    delete[] desktop;
    desktop = nullptr;

    createfiles(number - 1);
}
int main()
{
    createfiles(10);
    return 0;
}

1 Answers1

1

If the function call time(NULL) is executed several times in the same second (which is probably happening in your case), then it will return the same value every time.

This means that you are seeding the random number generator with the same value every time you attempt to generate a random string. As a consequence, rand will generate the same sequence of random numbers every time. This means that you are generating the same random string every time you call the function generateRandomUnicodeString.

If you attempt to create the same filename 10 times, then only the first time will succeed and the remaining 9 times will fail, because that file already exists.

The simplest fix to your problem would therefore be to only call srand only once in your program, not every time generateRandomUnicodeString is called. This is best done at the start of the function main.

That way, you will only have the problem of generating the same sequence of random numbers if you call main more than once in the same second (i.e. if you start the program twice in the same second). It will no longer be a problem if you call generateRandomUnicodeString several times in the same second.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39