How can I get/set an environment variable from a program?

How can I get/set an environment variable from a program?


Getting the value of an environment variable is done by using
getenv().




#include <stdlib.h>

char *getenv(const char *name);



Setting the value of an environment variable is done by using
putenv().




#include <stdlib.h>

int putenv(char *string);



The string passed to putenv must not be freed or made invalid,
since a pointer to it is kept by putenv(). This means that it
must either be a static buffer or allocated off the heap. The string
can be freed if the environment variable is redefined or deleted via
another call to putenv().



Remember that environment variables are inherited; each process has a
separate copy of the environment. As a result, you can't change the
value of an environment variable in another process, such as the shell.



Suppose you wanted to get the value for the TERM environment
variable. You would use this code:




char *envvar;

envvar=getenv("TERM");

printf("The value for the environment variable TERM is ");
if(envvar)
{
printf("%s\n",envvar);
}
else
{
printf("not set.\n");
}



Now suppose you wanted to create a new environment variable called
MYVAR, with a value of MYVAL. This is how you'd do it.




static char envbuf[256];

sprintf(envbuf,"MYVAR=%s","MYVAL");

if(putenv(envbuf))
{
printf("Sorry, putenv() couldn't find the memory for %s\n",envbuf);
/* Might exit() or something here if you can't live without it */
}






Home FAQ