Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing all environment variables in C / C++

Tags:

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?

like image 796
Jay Avatar asked Jan 18 '10 10:01

Jay


People also ask

How do I print all environment variables?

Using the printenv Command Or, if we run the command without arguments, it will display all environment variables of the current shell.

How do I get a list of all environment variables?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables.

How can I see all variables in CMD?

Select Start > All Programs > Accessories > Command Prompt. In the command window that opens, enter set. A list of all the environment variables that are set is displayed in the command window.

Can you export environment variables?

To export a environment variable you run the export command while setting the variable. We can view a complete list of exported environment variables by running the export command without any arguments. To view all exported variables in the current shell you use the -p flag with export.


1 Answers

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; } 
like image 50
Alex Brown Avatar answered Sep 16 '22 23:09

Alex Brown