Thursday, 24 July 2014

Setting and Getting Environment Variable in C

There are a number of way by which you can access environment variable in C. Most common of them is to declare as

main(int argc,char* argv[], char** envp)
view raw gistfile1.c hosted with ❤ by GitHub

envp contains all environment strings. Here is an example program:

#include<stdio.h>
int main(int argc, char* argv[], char* evnp[]) {
int i;
for(i=0; evnp[i]!=NULL; i++) {
printf("%s\n",evnp[i]);
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
We can also use external variable 'environ' to get all the environment variable.
Here is an example program:

#include<stdio.h>
extern char** environ;
int main(int argc, char* argv[]) {
int i;
for(i=0; environ[i]!=NULL; i++) {
printf("%s\n",environ[i]);
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
Also,there are function available in stdlib through which we can access any particular environment variable as well as add and modify them. getenv is use to get value of an environment variable whereas setenv is use to add and replace them. setenv also takes an optional parameter which specify whether we want to overwrite any existing variable or not.

Here is a sample program:

#include<stdio.h>
#include<stdlib.h>
void myGetenv (const char * name)
{
char * value = getenv (name);
if (! value) {
printf ("%s is not set.\n", name);
}
else {
printf ("%s = %s\n", name, value);
}
}
int main(int argc, char* argv[], char* evnp[]) {
// Variable is not set.
myGetenv ("myVar");
setenv ("myVar", "TestVal", 0);
myGetenv ("myVar");
// This doesn't change the value because "overwrite" is 0.
setenv ("myVar", "SecondValue", 0);
myGetenv ("myVar");
// This changes the value because "overwrite" is 1.
setenv ("myVar", "SecondValue", 1);
myGetenv ("myVar");
}
view raw gistfile1.c hosted with ❤ by GitHub
The output of above code would be:
myVar is not set.
myVar = TestVal
myVar = TestVal
myVar = SecondValue
view raw gistfile1.txt hosted with ❤ by GitHub


No comments:

Post a Comment