tags:

views:

382

answers:

9

How do I get the list of all environment variables in C and/or C++. I know that getenv can be used to read an environment variable, but how do I list them all?

A: 
int main(int argc, char* argv[], char* envp[]) {
   // loop through envp to get all environments as "NAME=val" until you hit NULL.
}
KennyTM
+3  A: 

i think you should check environ, "man environ"

Dyno Fu
http://www.opengroup.org/onlinepubs/007908799/xsh/environ.html
ephemient
+2  A: 

Your compiler may provide non-standard extensions to the main function that provides additional environment variable information. The MS compiler and most flavours of Unix have this version of main:

int main (int argc, char **argv, char **envp)

where the third parameter is the environment variable information - use a debugger to see what the format is - probably a null terminated list of string pointers.

Skizz
+1  A: 

LPTCH WINAPI GetEnvironmentStrings(void);

http://msdn.microsoft.com/en-us/library/ms683187%28VS.85%29.aspx

EDIT: only works on windows.

whunmr
A: 

If you're running on a Windows operating system then you can also call GetEnvironmentStrings() which returns a block of null terminated strings.

Len Holgate
A: 

In most environments you can declare your main as:

main(int argc,char* argv[], char** envp)

envp contains all environment strings.

Hope this helps.

Regards,

Sebastiaan

Sebastiaan Megens
+6  A: 

env is available as an argument to main, as envp - a null terminated array of strings:

int main(int argc, char **argv, char** envp)
{
  char** env;
  for (env = envp; *env != 0; env++)
  {
    char* thisEnv = *env;
    printf("%s\n", thisEnv);    
  }
}
Alex Brown