如何获取 %AppData% 路径为 std::string?

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

我读到可以使用 SHGetSpecialFolderPath(); 获取 AppData 路径。但是,它 returns 一个 TCHAR 数组。我需要一个 std::string.

如何转换为 std::string

更新

我读到可以使用 getenv("APPDATA"),但它在 Windows XP 中不可用。我想支持 Windows XP - Windows 10.

T类型表示SHGetSpecialFolderPath是一对函数:

  • SHGetSpecialFolderPathA 用于 Windows ANSI 编码的基于 char 的文本,以及

  • SHGetSpecialFolderPathW 对于基于 wchar_t 的 UTF-16 编码文本,Windows' “Unicode”。

ANSI 变体只是 Unicode 变体的包装器,它不能在所有情况下都在逻辑上产生正确的路径。

但这是您需要用于 char 基于数据的内容。


另一种方法是使用该函数的 wide 变体,并使用您熟悉的任何机制将宽文本结果转换为您选择的基于字节的 char 编码,例如UTF-8.

请注意,UTF-8 字符串不能直接用于通过 Windows API 打开文件等,因此这种方法涉及更多的转换,只是为了使用字符串。


但是,我建议在 Windows 中切换到宽文本。

为此,在包含<windows.h>之前定义宏符号UNICODE

这也是 Visual Studio 项目中的默认值。

您应该使用 SHGetSpecialFolderPathA() 让函数明确处理 ANSI 字符。

然后,照常将char的数组转换为std::string即可。

/* to have MinGW declare SHGetSpecialFolderPathA() */
#if !defined(_WIN32_IE) || _WIN32_IE < 0x0400
#undef _WIN32_IE
#define _WIN32_IE 0x0400
#endif

#include <shlobj.h>
#include <string>

std::string getPath(int csidl) {
    char out[MAX_PATH];
    if (SHGetSpecialFolderPathA(NULL, out, csidl, 0)) {
        return out;
    } else {
        return "";
    }
}

https://msdn.microsoft.com/en-gb/library/windows/desktop/dd374131%28v=vs.85%29.aspx

#ifdef UNICODE
    typedef wchar_t TCHAR;
#else
    typedef unsigned char TCHAR;
#endif

基本上你可以把这个数组转换成std::wstring。使用 std::wstring_convert.

转换为 std::string 很简单

http://en.cppreference.com/w/cpp/locale/wstring_convert

Typedef 字符串为 std::string 或 std::wstring,具体取决于您的编译配置。以下代码可能有用:

#ifndef UNICODE  
  typedef std::string String; 
#else
  typedef std::wstring String; 
#endif