//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<atlstr.h>
using namespace std;
int main()
{
//Suppose we want to have a temporary environment variable called "ZahidVar" whose value could be "120" or "140"
string varName("ZahidVar");
CString value;
DWORD len = GetEnvironmentVariable(varName.c_str(), value.GetBuffer(100), 100);
value.ReleaseBuffer();
if(len)
cout<<"Value of environment variable = "<<value<<endl;
else
cout<<"environment variable was empty"<<endl;
//Set the environment variable now
SetEnvironmentVariable("ZahidVar", "120");
len = GetEnvironmentVariable(varName.c_str(), value.GetBuffer(100), 100);
value.ReleaseBuffer();
if(len)
cout<<"Value of environment variable = "<<value<<endl;
else
cout<<"environment variable was empty"<<endl;
return 0;
}
The output is as follows:
It should be noted that the scope of this environment variable is temporary and will cease to exist once the program exits.
You can also look at this example to show you how to print all the environment variables.