获取windows登录用户的用户目录 C++

水深无声 2022-06-01 11:39 362阅读 0赞

网上各种std::getenv()等方法众多,实际上这个函数被认为是不安全函数,vs2013下连编译都无法通过。

其实Windows有自己的API函数:
DWORD WINAPI GetEnvironmentVariable(
In_opt LPCTSTR lpName,
Out_opt LPTSTR lpBuffer,
In DWORD nSize
);
官网地址:http://msdn.microsoft.com/en-us/library/ms683188(VS.85).aspx


简单使用示例

  1. std::string path= "";
  2. const char* homeProfile = "USERPROFILE";
  3. char homePath[1024] = {
  4. 0};
  5. unsigned int pathSize = GetEnvironmentVariable(homeProfile, homePath, 1024);
  6. if (pathSize == 0 || pathSize > 1024)
  7. {
  8. // 获取失败 或者 路径太长
  9. int ret = GetLastError();
  10. }
  11. else
  12. {
  13. path = std::string(homePath);
  14. }

发表评论

表情:
评论列表 (有 0 条评论,362人围观)

还没有评论,来说两句吧...

相关阅读