How can I read the whole environment?

How can I read the whole environment?


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.)






Home FAQ