In this article, I will discuss some of the most simple ways to access environment variables in C language programming.
Approach 1
In this method, we simply used the environ
variable by extending it using the extern keyword.
Code
#include <stdio.h>
// https://man7.org/linux/man-pages/man7/environ.7.html
extern char **environ;
int main(int argc, char **argv) {
// list out all the environment variables
for (int i=0; environ[i]!=NULL; i++) {
printf("%d: %s\n", i, envp[i]);
}
return 0;
}
Check out environ
man page for more info.
Approach 2
Most of the students don't know that the main
function can also receive a third argument which is nothing but the array of environment variables.
NOTE: The third argument may not support all compilers. But it should work on the latest compiler versions.
Code
#include <stdio.h>
int main(int argc, char **argv, char **envp) {
// list out all the environment variables
for (int i=0; envp[i]!=NULL; i++) {
printf("%d: %s\n", i, envp[i]);
}
return 0;
}
Approach 3
In this method, we use the getenv
and setenv
functions defined
getenv
takes one argument which is the environment variable name and returns a null-terminated char pointer. If the passed name does not exist, it returns NULL
.
setenv
takes three arguments. The first one is the environment variable name, the second is its value and the third one is an int flag which if non-zero overwrites the already existing environment variable with the same name.
NOTE:
setenv
doesn't set the environment variable permanently but for the current process and its child process only. It meanssetenv
the environment variables are visible only in the current process and its child ones.
Check out some other functions like clearenv
, and putenv
in man page for more operations.
Code
#include <stdio.h>
#include <stdlib.h> // setenv, getenv
int main(int argc, char **argv) {
char *user = getenv("USER"),
*hosttype = getenv("HOSTTYPE"),
*hostname = getenv("HOSTNAME");
printf("USER: %s\n", user ? user : "null");
printf("HOSTTYPE: %s\n", hosttype ? hosttype : "null");
printf("HOSTNAME: %s\n", hostname ? hostname : "null");
setenv("USER", "namantam1", 1);
printf("updated USER: %s\n", getenv("USER"));
return 0;
}
Output
USER: naman
HOSTTYPE: x86_64
HOSTNAME: null
updated USER: namantam1
Application
- We can set log verbosity based on the environment variable.
- One can set the environment variable in the parent process and access the same in its child process. Check out this article to know how to clone the current process into a child process.
❤️Thank you so much for reading this article. I'm a passionate engineering student learning new things so If you find any mistakes or have any suggestions please let me know in the comments.
Also, consider sharing and giving a thumbs up If this post helps you in any way.
Top comments (0)