获取windows登录用户的用户目录 C++
网上各种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
简单使用示例
std::string path= "";
const char* homeProfile = "USERPROFILE";
char homePath[1024] = {
0};
unsigned int pathSize = GetEnvironmentVariable(homeProfile, homePath, 1024);
if (pathSize == 0 || pathSize > 1024)
{
// 获取失败 或者 路径太长
int ret = GetLastError();
}
else
{
path = std::string(homePath);
}
还没有评论,来说两句吧...