I have the following code:
// Fetch Local App Data folder path.
PWSTR localAppData = (PWSTR) malloc(128);
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &localAppData);
// Find out the absolute path to chrome.exe
stringstream ss;
ss << localAppData << "/Google/Chrome/Application/chrome.exe";
The result of stringstreamer’s .str() is 008F6788/Google/Chrome/Application/chrome.exe, which is wrong.
I can’t seem to get stringstreamer to work, neither do strcat or wcsncat due to type incompatibilities.
How do I cast this PWSTR to string?
1. Yuk!
Microsoft says:
So let’s get that horrid nonsense out of your testcase, and lose the C rubbish:
2. Warning!
There is a serious flaw here.
SHGetKnownFolderPathactually sets the value of the pointer you give it to point to memory that it allocated. Your code has a memory leak, and my last snippet frees the memory subtly wrongly.Let’s fix that by reading the documentation:
Now, on with the show.
3. Wide characters
The syntax issue with your code is that localAppData is a
wchar_t, but normalstringstreams work onchar.Fortunately, there is a wide-char variant called
wstringstreamthat useswchar_tinstead.(Note that this means your literal will have to be built out of
wchar_ts, too, using theLstring literal prefix.)And now the final code: