Question

Dealing with these insane strings and arrays is giving me a headache...

Here's my code so far

wchar_t mypath[MAX_PATH];
wchar_t temppath[MAX_PATH];

GetModuleFileName(0, mypath, MAX_PATH);
GetTempPath(MAX_PATH, temppath);
CreateDirectory(???, NULL);

The first two windows API functions use the LPWSTR variable. The third uses LPCWSTR. What's the major difference? After I get the path for the TEMP directory, I want to create a new directory inside it called "test". This means I need to append (L"test") to my "temppath" variable. Can someone give me some tips on how to use these arrays. This is what makes C++ a pain. Why couldn't everyone just settle on one data type for strings. How is wchar_t even useful? It's so hard to use and manipulate.

Thanks guys!

Was it helpful?

Solution 2

Use PathCombine(), eg:

wchar_t temppath[MAX_PATH+1] = {0};
GetTempPath(MAX_PATH, temppath);

wchar_t mypath[MAX_PATH+8] = {0};
PathCombineW(mypath, temppath, L"test");

CreateDirectoryW(mypath, NULL);

OTHER TIPS

The first two windows API functions use the LPWSTR variable. The third uses LPCWSTR. What's the major difference?

LPCWSTR is a const version of LPWSTR:

  • From LPCWSTR:

    typedef const wchar_t* LPCWSTR; 
    
  • From LPWSTR:

    typedef wchar_t* LPWSTR, *PWSTR;
    

I want to create a new directory inside it called "test". This means I need to append (L"test") to my "temppath" variable.

Use a std::wostringstream:

std::wostringstream wos;
wos << temppath  << L"\\test";
std::wstring fullpath(wos.str());

or just a std::wstring (as suggested by chris in the comments):

std::wstring fullpath(std::wstring(temppath) + L"\\test");

to produce a concatenated version. Then use c_str() as the argument to CreateDirectory():

if (CreateDirectory(fullpath.c_str(), NULL) ||
    ERROR_ALREADY_EXISTS == GetLastError())
{
    // Directory created or already existed.
}
else
{
     // Failed to create directory.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top