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 theenviron
variable by extending it using the extern keyword.
Code
#include<stdio.h>// https://man7.org/linux/man-pages/man7/environ.7.htmlexternchar**environ;intmain(intargc,char**argv){// list out all the environment variablesfor(inti=0;environ[i]!=NULL;i++){printf("%d: %s\n",i,envp[i]);}return0;}
Check outenviron
man page for more info.
Approach 2
Most of the students don't know that themain
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>intmain(intargc,char**argv,char**envp){// list out all the environment variablesfor(inti=0;envp[i]!=NULL;i++){printf("%d: %s\n",i,envp[i]);}return0;}
Approach 3
In this method, we use thegetenv
andsetenv
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 returnsNULL
.
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 likeclearenv
, andputenv
inman page for more operations.
Code
#include<stdio.h>#include<stdlib.h> // setenv, getenvintmain(intargc,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"));return0;}
Output
USER: namanHOSTTYPE: x86_64HOSTNAME: nullupdated 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 outthis 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)
For further actions, you may consider blocking this person and/orreporting abuse