Search code examples
c++stringwindowspathappdata

How to get %AppData% path as std::string?


I've read that one can use SHGetSpecialFolderPath(); to get the AppData path. However, it returns a TCHAR array. I need to have an std::string.

How can it be converted to an std::string?

Update

I've read that it is possible to use getenv("APPDATA"), but that it is not available in Windows XP. I want to support Windows XP - Windows 10.


Solution

  • The T type means that SHGetSpecialFolderPath is a pair of functions:

    • SHGetSpecialFolderPathA for Windows ANSI encoded char based text, and

    • SHGetSpecialFolderPathW for UTF-16 encoded wchar_t based text, Windows' “Unicode”.

    The ANSI variant is just a wrapper for the Unicode variant, and it can not logically produce a correct path in all cases.

    But this is what you need to use for char based data.


    An alternative is to use the wide variant of the function, and use whatever machinery that you're comfortable with to convert the wide text result to a byte-oriented char based encoding of your choice, e.g. UTF-8.

    Note that UTF-8 strings can't be used directly to open files etc. via the Windows API, so this approach involves even more conversion just to use the string.


    However, I recommend switching over to wide text, in Windows.

    For this, define the macro symbol UNICODE before including <windows.h>.

    That's also the default in a Visual Studio project.