GetEnvironmentVariable and GetEnvironmentStrings usage in Win32

   Environment variables are used by variety of programs. Each process loaded in Windows will have access to its block of environment variables. While windows uses the environment variables for storing values like PATH, user names etc., these data will be used by other processes running on windows. This article explains how to use win32 GetEnvironmentVariable and GetEnvironmentStrings functions for extracting environment block data.

GetEnvironmentVariable – Usage Sample in Win32:


      #include <stdio.h>
#include <windows.h>

int main()
{
char l_strSingleVal[20];
GetEnvironmentVariable(“VariableName”, l_strSingleVal,20);

printf(“VariableName: %sn”,l_strSingleVal);
}


GetEnvironmentStrings – Usage Sample in Win32:

   GetEnvironmentStrings retrieves the whole block of environment variables related to the calling process. It takes no parameters and returns a pointer to the environment block of the calling process. The number of character strings inside the block should be ascertained first and then only the manipulation/display of the strings should be carried out.


       #include <stdio.h>
#include <windows.h>

int main()
{

char *l_EnvStr;
l_EnvStr = GetEnvironmentStrings();

LPTSTR l_str = l_EnvStr;

int count = 0;
while (true)
{
if (*l_str == 0) break;
while (*l_str != 0) l_str++;
l_str++;
count++;
}

for (int i = 0; i < count; i++)
{
printf(“%sn”, l_EnvStr);
while(*l_EnvStr != ”)
l_EnvStr++;
l_EnvStr++;
}

FreeEnvironmentStrings(l_EnvStr);
return 0;
}


   The above sample code can retrieve the whole environment block and display it in the console.

GetEnvironmentVariable is used to extract a single value from the environment block of the calling process. The values will be returned as character strings.