Question

I am learning C++. I need to print the environment value of a particular environment variable. I am finding examples to check whether a environment variable is defined or not. But how to print the environment value.

GetEnvironmentVariable(_T("path"), Buffer, _MAX_PATH); returns DWORD and it is printing some integer but I need to print the exact value something like "C:\programfiles\windows".

In C# I can do this using

string abc = Environment.GetEnvironmentVariable("PATH");
cout<<a;

How to do this in VC++. Thanks

Was it helpful?

Solution

_MAX_PATH is not probably enough to hold the whole value. You should first call the method with a nullptr and size 0 to get the size required and then allocate a buffer of that size.

auto size = GetEnvironmentVariableA("PATH", nullptr, 0);
std::string Buffer(size, 0);
GetEnvironmentVariableA("PATH", &Buffer[0], size);
std::cout << Buffer << std::endl;

UPDATE: For pre C++11 compilers:

DWORD size = GetEnvironmentVariableA("PATH", NULL, 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top