Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 890
dB' Avatar asked May 27 '13 02:05

dB'


1 Answers

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;
}
like image 195
icktoofay Avatar answered Oct 03 '22 08:10

icktoofay