Will the thing is I have to use the path USERPROFILE for another part of my program which takes a LPCSTR |
Can you change that one thing to use a LPCWSTR? That would be the easiest/best solution here.
the only thing I don't get is how to not use wchar_t |
WinAPI funcitons have 3 forms: One which takes 'char' strings (LPCSTR), one which takes wchar_t strings (LPCWSTR) and one which takes TCHAR strings (LPCTSTR). The functions all follow the same naming scheme.
Example:
MessageBox() <- takes LPCTSTR (TCHAR)
MessageBoxW() <- takes LPCWSTR (wchar_t)
MessageBoxA() <- takes LPCSTR (char)
My advise is pick one and use it everywhere.
Note that I've heard rumors that the 'A'/char functions are being deprecated, but I haven't confirmed that and I'm not sure if I believe it.
---------------------------
As for converting between wchar_t and char, it's not really as simple as a straight copy. 'char' isn't bit enough to hold all the same information as 'wchar_t', so if you just do a normal copy from wchar_t to char, you'll lose information. This doesn't matter for plain ASCII strings, so you might not notice (but if you are only dealing with ASCII strings, then you don't need to use wchar_t anyway)
WinAPI treats wchar_t strings as Unicode (UTF-16) encoding. But it can treat char strings any number of ways... by assigning them what's called a "code page". The lower 128 characters are always the same ASCII characters, but the upper 128 chars can change depending on what the code page is set to. If you want your char strings to be able to hold any and all characters, you'd want to set the code page to UTF-8.
Converting UTF-16 to UTF-8 and vice versa isn't exactly trivial. Fortunately WinAPI offers some helper functions for it:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd319072%28v=vs.85%29.aspx <- utf-8 to utf-16
http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130%28v=vs.85%29.aspx <- utf-16 to utf-8
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
wchar_t utf16[300] = L"A wide / UTF-16 string";
char utf8[300];
// convert the UTF-16 string to a UTF-8 string
WideCharToMulitByte(
CP_UTF8, // we want UTF-8 encoding
0, // no other flags
utf16, // the source string
-1, // source string is null terminated, so we give -1 for the size
utf8, // destination string
300, // size of destination buffer
NULL,NULL); // last 2 params are useless for UTF conversions
// now utf16 has been copied to utf8. To convert back:
MultiByteToWideChar(
CP_UTF8, // src string is UTF8
0, // no other flags
utf8, // source string
-1, // null terminated, so no need to give a size
utf16, // dest string
300 ); // dest size
|