Environment Variables
This section describes the functions that allow you to access and manipulate environment variables within the Windows operating system. Environment variables provide a dynamic way to store and retrieve configuration information used by applications and the system itself.
Overview
Environment variables are key-value pairs that are part of the operating system's environment. They can be used to specify paths, configuration settings, and other runtime parameters. Understanding how to interact with them is crucial for developing robust and adaptable Windows applications.
Environment variables can be set at different scopes:
- System Environment Variables: Affect all users on the system.
- User Environment Variables: Affect only the current user.
- Process Environment Variables: Specific to a running process.
Key Functions
GetEnvironmentVariable
Retrieves the value of a specified environment variable for the current process.
Syntax:
DWORD GetEnvironmentVariable(
LPCTSTR lpName,
LPTSTR lpBuffer,
DWORD nSize
);
Parameters:
lpName
: The name of the environment variable.lpBuffer
: A buffer that receives the variable's value.nSize
: The size of the buffer in characters.
Return Value: The length of the string copied to lpBuffer, not including the null terminator. If the buffer is not large enough, the return value is the required buffer size in characters, including the null terminator.
SetEnvironmentVariable
Creates, modifies, or deletes an environment variable. The variable is associated with the current process.
Syntax:
BOOL SetEnvironmentVariable(
LPCTSTR lpName,
LPCTSTR lpValue
);
Parameters:
lpName
: The name of the environment variable to set.lpValue
: The new value for the environment variable. If this parameter is NULL, the variable is deleted.
Return Value: Nonzero if the function succeeds or the variable is deleted, zero otherwise.
ExpandEnvironmentStrings
Expands environment variables in a specified string.
Syntax:
DWORD ExpandEnvironmentStrings(
LPCTSTR lpSrc,
LPTSTR lpDst,
DWORD nSize
);
Parameters:
lpSrc
: The input string containing environment variables.lpDst
: A buffer that receives the expanded string.nSize
: The size of the buffer in characters.
Return Value: The length of the expanded string, not including the null terminator. If the buffer is not large enough, the return value is the required buffer size in characters, including the null terminator.
Common Environment Variables
Here are some commonly used environment variables:
%SystemRoot%
: The root directory of the current Windows installation (e.g.,C:\Windows
).%ProgramFiles%
: The installation directory for program files.%PATH%
: A list of directories where the system looks for executable files.%TEMP%
and%TMP%
: Temporary file directories.%USERNAME%
: The name of the current user.