How to read an environment variable
Posted: Thu Sep 17, 2015 10:23 am
I wanted to get the value of the environment variable HOMEPATH.
I've found that WinApi.GetEnvironmentVariableW provides that.
But in order to make it easier, I've written a wrapper function:
Regards,
Manuel
I've found that WinApi.GetEnvironmentVariableW provides that.
But in order to make it easier, I've written a wrapper function:
Code: Select all
PROCEDURE EnvVarValue* (IN pName: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR;
(* Returns the value of the environment variable named pName, e.g. EnvVarValue('HOMEPATH') *)
VAR arrOut: POINTER TO ARRAY OF CHAR;
envVarName, envVarValue: WinApi.PtrWSTR;
lenValue: INTEGER;
BEGIN
envVarName := pName;
NEW(arrOut, 80); envVarValue := arrOut^;
lenValue := WinApi.GetEnvironmentVariableW(envVarName, envVarValue, LEN(arrOut));
IF lenValue = 0 THEN
(* There is no such environment variable; or error *)
envVarValue := ""
ELSIF lenValue > LEN(arrOut) THEN
(* The out array is not large enough to store the value of the environment variable. Now, the out array will be allocated with the exact size. *)
NEW(arrOut, lenValue); envVarValue := arrOut^;
lenValue := WinApi.GetEnvironmentVariableW(envVarName, envVarValue, LEN(arrOut));
ASSERT(lenValue <= LEN(arrOut), 60)
END;
arrOut^ := envVarValue$;
RETURN arrOut
END EnvVarValue;
Manuel