How to list all environment variables in a c / C ++ application

I know that when programming in C ++ I can access individual environment variables using getenv .

I also know that in the os x terminal I can display ALL current environment variables using env .

I'm interested in getting a complete list of environment variables available for my current C ++ program. Is there a c / C ++ function that will list them? In other words, is there a way to call env from my C ++ code?

+6
source share
3 answers

Use the global environ variable. This is a null-end pointer for an array of strings in the format name=value . Here's a miniature clone of env :

 #include <stdlib.h> #include <stdio.h> extern char **environ; int main(int argc, char **argv) { for(char **current = environ; *current; current++) { puts(*current); } return EXIT_SUCCESS; } 
+10
source

You can use the envp argument for main :

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

and as a bonus, apparently on OSX you have apple , which gives you other information provided by the OS:

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

But what is it used for? Well, Apple can use the apple vector to pass any β€œhidden” parameters that they want for any program. And they really use it. Currently apple [0] contains the path where the executable binary was found on disk. What are you saying? How is apple [0] different from argv [0]? The difference is that argv [0] can be set to any arbitrary value when execve (2) is called. For example, shells often distinguish an input shell from a regular shell by launching an input shell with the first character in argv [0], which is a -

+11
source

Oops, I forgot that system allows you to execute terminal commands.

This snippet gives me what I need:

 std::cout << "List of environment variables: << std::endl; system("env"); 
0
source

Source: https://habr.com/ru/post/945902/


All Articles