getenv, _wgetenv

From RAD Studio
Jump to: navigation, search

Go Up to stdlib.h Index


Header File

stdlib.h

Category

Process Control Routines

Prototype

char *getenv(const char *name);

wchar_t *_wgetenv(const wchar_t *name);

Description

Gets an environment variable from the system environment.

The environment consists of a series of entries that are of the form name=string\0.

getenv returns the value of a specified variable. name can be either uppercase or lowercase. name must not include the equal sign (=). If the specified environment variable does not exist, getenv returns a NULL pointer.

To modify an environment variable, use putenv, _wputenv.

Note: The getenv function returns a pointer to the environment variable, not a copy of the variable content. Thus it is possible to modify the content of the variable using the obtained pointer, like in the following example:


This is not the recommended way to change the content of an environment variable.

char *p;
p = getenv("PROCESSOR_ARCHITECTURE");
puts(p);
strcpy(p, "F20");
p = getenv("PROCESSOR_ARCHITECTURE"); // has no effect on p
puts(p);

Possible output:

x86
F20

Return Value

On success, getenv returns the value associated with the name.

If the specified name is not defined in the environment, getenv returns a NULL pointer.

Example

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

int main(void)
{
   char *path, *ptr;
   int i = 0;
   /* get the current path environment */
   ptr = getenv("PATH");
   /* set up new path */
   path = (char *) malloc(strlen(ptr)+15);
   strcpy(path,"PATH=");
   strcat(path,ptr);
   strcat(path,";c:\\temp");
   /* replace the current path and display current environment */
   putenv(path);
   while (_environ[i]){
       printf("%s\n",_environ[i++]);
   }
   return 0;
}

Portability

POSIX Win32 ANSI C ANSI C++

getenv

+

+

+

+

_wgetenv

+


See Also