How to list all environment variables in a c/c++ app
Asked Answered
M

3

11

I know that when programming in c++ I can access individual environment variables with getenv.

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

I'm interested in getting a complete list of the environment variables that are available to my running 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?

Merrymaker answered 27/5, 2013 at 2:16 Comment(2)
The magic is here: env.c.Checkered
The shell command is env, not ENV (I've edited your question to fix that).Gaylagayle
T
17

Use the environ global variable. It is a null-terminated pointer to 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;
}
Toft answered 27/5, 2013 at 2:25 Comment(1)
Indeed. man getenv has at the bottom (on OS X, which the OP mentions) a SEE ALSO section which mentions environ(7). So man environ provides a manpage which explains this. apropos environment includes this page, too. This isn't meant to be RTFM, but a hint to the OP that the SEE ALSO sections of manpages can be worth checking.Stephie
S
14

You may be able to use the non-portable envp argument to main:

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

and as a bonus apparently on OSX you have apple which gives you other OS supplied info:

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 whatever "hidden" parameters they want to any program. And they do actually use it, too. Currently, apple[0] contains the path where the executing binary was found on disk. What's that you say? 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 differentiate a login shell from a regular shell by starting login shells with the first character in argv[0] being a -

Selfregard answered 27/5, 2013 at 2:20 Comment(0)
M
0

Whoops, I forgot that system lets you execute terminal commands.

This snippet gives me what I need:

std::cout << "List of environment variables: << std::endl;
system("env");
Merrymaker answered 27/5, 2013 at 2:23 Comment(1)
That doesn't make the variable available to your program, it just prints them to standard output.Gaylagayle

© 2022 - 2024 — McMap. All rights reserved.