Environment Variables: Example 3
The following example retrieves the process's environment block using GetEnvironmentStrings() and prints the contents to the console.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
int wmain(int argc, WCHAR **argv)
{
LPTSTR lpszVariable;
LPWCH lpvEnv;
// Get a pointer to the environment block
lpvEnv = GetEnvironmentStrings();
// If the returned pointer is NULL, exit
if (lpvEnv == NULL)
{
wprintf(LGetEnvironmentStrings() failed! Error %d\n, GetLastError());
return 0;
}
else
wprintf(LGetEnvironmentStrings() is OK!\n\n);
// Variable strings are separated by NULL byte, and the block is
// terminated by a NULL byte
lpszVariable = (LPTSTR)lpvEnv;
while(*lpszVariable)
{
wprintf(L%s\n, lpszVariable);
lpszVariable += lstrlen(lpszVariable) + 1;
}
// Frees a block of environment strings
if(FreeEnvironmentStrings(lpvEnv) != 0)
wprintf(LFreeEnvironmentStrings() - a block of environment strings was freed!\n);
else
wprintf(LFreeEnvironmentStrings() failed, error %u\n, GetLastError());
return 1;
}
Build and run the project. The following screenshot is a sample output.