| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 */
}
|
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
If you don't know the names of the environment variables, then the
getenv() function isn't much use. In this case, you have to dig
deeper into how the environment is stored.
A global variable, environ, holds a pointer to an array of
pointers to environment strings, each string in the form
"NAME=value". A NULL pointer is used to mark the end of
the array. Here's a trivial program to print the current environment
(like printenv):
#include <stdio.h>
extern char **environ;
int main()
{
char **ep = environ;
char *p;
while ((p = *ep++))
printf("%s\n", p);
return 0;
}
|
In general, the environ variable is also passed as the third,
optional, parameter to main(); that is, the above could have been
written:
#include <stdio.h>
int main(int argc, char **argv, char **envp)
{
char *p;
while ((p = *envp++))
printf("%s\n", p);
return 0;
}
|
However, while pretty universally supported, this method isn't actually defined by the POSIX standards. (It's also less useful, in general.)
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] |
This document was generated on September, 10 2007 using texi2html 1.77.