【发布时间】:2021-08-09 21:02:48
【问题描述】:
所以我一直在试图弄清楚如何找到一个环境变量并用 c++ 在屏幕上打印出来 但在过去的 3 个小时左右,我一直被卡住。当我打印出 currentDesktop 变量时,它只打印出“/Desktop”。但我正在寻找的是它前面的用户名。 我一直在阅读 Microsoft 论坛上有关 GetEnviromentVariable 函数的文档,这就是我迄今为止想出的。 非常感谢您的帮助,因为我还没有那么有经验,Thx。
#include <iostream>
#include <string>
#include <windows.h>
#include <fstream>
#define BUFSIZE 4096
using namespace std;
int main()
{
LPCWSTR Env = L"%USERPROFILE";
LPTSTR pszOldVal;
string IPADD;
pszOldVal = (LPTSTR)malloc(BUFSIZE * sizeof(TCHAR));
if (NULL == pszOldVal)
{
printf("Out of memory\n");
return FALSE;
}
string currentDesktop = GetEnvironmentVariable(Env,pszOldVal,BUFSIZE) + "\\Desktop";
cout << currentDesktop;
return 0;
}
【问题讨论】:
-
std::getenv 的文档有一个易于理解的示例。
-
如果你想要用户,为什么不使用
%USERPROFILE%? -
@CPPNEWBIE 仔细阅读您的代码。它包含什么,而不是你认为它做了什么。
-
啊哈,在将
"\\Desktop"添加到返回的结果之前,您忘记将GetEnvironmentVariable(Env,pszOldVal,BUFSIZE)转换为std::string。GetEnvironmentVariable返回char*,而不是std::string -
@NathanOliver "
GetEnvironmentVariable返回char*" - 不,它需要char[]并且返回 i> 一个DWORD,指定将多少个字符复制到char[]。你正在考虑(std::)getenv()。
标签: winapi visual-c++ environment-variables