Is there a way to enumerate environment variables and retrieve values using C?
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.
The most used command to displays the environment variables is printenv . If the name of the variable is passed as an argument to the command, only the value of that variable is displayed. If no argument is specified, printenv prints a list of all environment variables, one variable per line.
The C/C++ environment variables define the characteristics of a specific environment. Environment variables are inherited from system definitions, but can be modified at an application level without affecting the environment of other applications or the system settings.
The Global environment variables of your system are stored in /etc/environment . Any changes here will get reflected throughout the system and will affect all users of the system.
Take a look at the environ
global variable.
extern char **environ;
It might be defined in unistd.h
(take a look at the environ (5)
man page above).
Here's a little code demo I wrote:
#include <stdio.h>
extern char **environ;
int main()
{
for (char **env = environ; *env; ++env)
printf("%s\n", *env);
}
Here's how to use it:
matt@stanley:~/Desktop$ make enumenv CFLAGS=-std=c99
cc -std=c99 enumenv.c -o enumenv
matt@stanley:~/Desktop$ ./enumenv
ORBIT_SOCKETDIR=/tmp/orbit-matt
SSH_AGENT_PID=1474
TERM=xterm
SHELL=/bin/bash
... (so forth)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With