C Standard Library

C <stdlib.h> - getenv() Function



The C <stdlib.h> getenv() function returns a C-string containing the value of the environment variable whose name is specified as argument. If the requested variable is not found, the function returns a null pointer.

The pointer returned points to an internal memory block, whose content or validity may be altered by further calls to getenv() (but not by other library functions).

The string pointed by the pointer returned by this function shall not be modified by the program. Some systems and library implementations may allow to change environmental variables with specific functions (putenv, setenv and unsetenv), but such functionality is non-portable.

Syntax

char* getenv (const char* env_var);

Parameters

env_var Specify a null-terminated character string containing the name of the requested variable. Depending on the platform, this may either be case sensitive or not.

Return Value

Returns a C-string with the value of the environmental variable or null pointer if such variable is not found.

Example:

The example below shows the usage of <stdlib.h> getenv() function.

#include <stdio.h>
#include <stdlib.h>

int main (){
  char* env_p;
  env_p = getenv("PATH");
  if (env_p != NULL)
    printf ("The path is: %s", env_p);

  return 0;
}

The output of the above code will be similar to:

The path is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

❮ C <stdlib.h> Library