Printing all environment variables in C / C++
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?
The environment variables are made available to main()
as the envp
argument - a null terminated array of strings:
int main(int argc, char **argv, char **envp)
{
for (char **env = envp; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s\n", thisEnv);
}
return 0;
}
#include <stdio.h>
extern char **environ;
int main() {
char **s = environ;
for (; *s; s++) {
printf("%s\n", *s);
}
return 0;
}
I think you should check environ
. Use "man environ".
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.
LPTCH WINAPI GetEnvironmentStrings(void);
http://msdn.microsoft.com/en-us/library/ms683187%28VS.85%29.aspx
EDIT: only works on windows.