3

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!

hmjd
  • 120,187
  • 20
  • 207
  • 252
43.52.4D.
  • 950
  • 6
  • 14
  • 28

2 Answers2

6

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.
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Wouldn't `std::wstring(temppath) + L"\\test"` be easier (even better if `std::wstring` is used in the first place)? – chris Jul 05 '13 at 20:22
  • @hmjd great answer! I accepted the other one though, because it was simpler, but I still +1'd this! – 43.52.4D. Jul 05 '13 at 22:06
4

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);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770