Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetEnvironmentVariableA() usage

I am working on a C++ Console Application in Visual Studio 2012 on Windows 7 and I want to get the values of some environment variables from within the application.
Here is what I've tried so far -:

int main()
{
    char a[1000];
    int s=GetEnvironmentVariableA("HOME",a,1000);
}  

However, I am getting the value of s to be 0, indicating that variable "HOME" does not exist.
Also, getenv("HOME") returns NULL too.
So, what is the correct procedure of doing this ?

like image 981
Anmol Singh Jaggi Avatar asked Mar 19 '23 09:03

Anmol Singh Jaggi


1 Answers

What this program is telling you, most likely, is that your process environment does not contain a variable named HOME. Note that HOME is not a variable that you would expect to be defined, unless you have taken steps to define it. Either by adding it to the system's environment, or by specifying a bespoke environment when creating the process.

The documentation says the following about the return value:

If the function succeeds, the return value is the number of characters stored in the buffer pointed to by lpBuffer, not including the terminating null character.

If lpBuffer is not large enough to hold the data, the return value is the buffer size, in characters, required to hold the string and its terminating null character and the contents of lpBuffer are undefined.

If the function fails, the return value is zero. If the specified environment variable was not found in the environment block, GetLastError returns ERROR_ENVVAR_NOT_FOUND.

So, if the function returns 0, do as the documentation says. Call GetLastError to find out why the function call failed.

But as I said, with probability very close to 1, the reason will simply be that your process environment has not defined a variable named HOME.

As to how you move forward, most likely you are looking for a location in the user's profile. Exactly how you do this will depend on where in the profile you wish to store/load the file. One of the APIs related to CSIDL or known folder IDs will serve your needs.

like image 199
David Heffernan Avatar answered Mar 28 '23 01:03

David Heffernan