I want concatenate a random string with a directory name and the final result must be something like this:
C:\Program Files (x86)\AAAFFF1334
On following code this part: "AAAFFF1334" comes strange characters see:
What must be made to fix this?
TCHAR mydir[MAX_PATH];
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum)-1)];
}
s[len] = 0;
}
// main
TCHAR szProgramFiles[MAX_PATH];
HRESULT hProgramFiles = SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, szProgramFiles);
char str;
gen_random(&str, 10);
wsprintf(mydir, TEXT("%s\\%s"), szProgramFiles, str);
gen_random
should get char array with at least 11 characters (10 for size + 1 for terminating null).
So it should be:
char str[10+1]; //or char str[11];
gen_random(str, 10);
in addition, the format string should be: "%s\\%hs"
, the first is TCHAR*
type (if UNICODE defined wchar_t*
if not char*
) the second is always char*
type.
hs, hS
String. This value is always interpreted as type LPSTR, even when the calling application defines Unicode.
LPSTR
= always char*
LPWSTR
= always wchar_t*
LPTSTR
= TCHAR*
(if UNICODE defined: wchar_t*
, else: char*
)