The Windows Processes and Threads 23






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.


Environment Variables: Program Example 3 - Creating new Win32 C++ console application project in Visual C++ .NET


Then, add the source file and give it a suitable name.


Environment Variables: Program Example 3 - Adding new C++ source file for C++ source code to the existing C++ project


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(L"GetEnvironmentStrings() failed! Error %d\n", GetLastError());

        return 0;



            wprintf(L"GetEnvironmentStrings() is OK!\n\n");


    // Variable strings are separated by NULL byte, and the block is

    // terminated by a NULL byte

    lpszVariable = (LPTSTR)lpvEnv;




        wprintf(L"%s\n", lpszVariable);

        lpszVariable += lstrlen(lpszVariable) + 1;


    // Frees a block of environment strings

    if(FreeEnvironmentStrings(lpvEnv) != 0)

            wprintf(L"FreeEnvironmentStrings() - a block of environment strings was freed!\n");


            wprintf(L"FreeEnvironmentStrings() failed, error %u\n", GetLastError());

    return 1;



Build and run the project. The following screenshot is a sample output.


Environment Variables: Program Example 3 - A sample console program output in action




< Processes & Threads 22 | Win32 Process & Thread Programming | Win32 Programming | Processes & Threads 24 >