# Retrieving environment variables in C

The function in charge of retrieving environment variables in C is getenv. getenv takes a string representing the environment variable name as its only argument and returns a pointer to the corresponding value. If the environment variable name passed in does not exist, getenv returns NULL.

## Using getenv

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #include #include #define BUFSIZE 80 int main(){ char path[BUFSIZE]; char *envvar = "PATH"; // Make sure envar actually exists if(!getenv(envvar)){ fprintf(stderr, "The environment variable %s was not found.\n", envvar); exit(1); } // Make sure the buffer is large enough to hold the environment variable // value. if(snprintf(path, BUFSIZE, "%s", getenv(envvar)) >= BUFSIZE){ fprintf(stderr, "BUFSIZE of %d was too small. Aborting\n", BUFSIZE); exit(1); } printf("PATH: %s\n", path); return 0; } 

raw source

First, we check the return value of getenv to make sure the environment variable even exists. Then, we use snprintf to make sure our path buffer actually has enough space to hold the value of our environment variable. Since snprintf returns the number of bytes that would be written to our path buffer if it had infinite space, a simple comparison with BUFSIZE lets us know if our buffer can hold the value.