Answer: An ‘Environment’ is an implementation-defined list of NAME/VALUE pairs maintained by the O.S.. Standard defines specific meanings to “Environment Variables”. Not all implementations necessarily define same set of Environment Variables but they must define same meanings to whatever Environment Variables they have. ‘getenv()’ function is declared in ‘stdlib.h’ header and prototyped as below
char *getenv(char const *NAME);
This function searches for NAME environment variable in the list and returns its value. Notice here that program must not modify value of NAME variable. Let’s write a C program and attempt to access several environment variables, for example,
/* getenv.c -- program accesses environment variables */ #include <stdio.h> #include <stdlib.h> #include <assert.h> int main(void) { char *str; /* attempt to access environment variables using getenv() */ assert((str = getenv("HOME")) != NULL); printf("Value of \"HOME Environmemt Variable\" : %s\n", str); assert((str = getenv("PATH")) != NULL); printf("Value of \"PATH Environmemt Variable\" : %s\n", str); assert((str = getenv("LOGNAME")) != NULL); printf("Value of \"LOGNAME Environmemt Variable\" : %s\n", str); /* attempt to access variable of ours' choice */ assert((str = getenv("MELLO")) != NULL); printf("Value of \"MELLO Environmemt Variable\" : %s\n", str); return 0; }
Observe the output below
Value of "HOME Environmemt Variable" : /root Value of "PATH Environmemt Variable" : /usr/lib64/ccache:/usr/local/sbin: /usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin Value of "LOGNAME Environmemt Variable" : root a.out: getenv.c:20: main: Assertion `(str = getenv("MELLO")) != ((void *)0)' failed. Aborted (core dumped)
Notice that ‘getenv()’ takes ‘NAME environment variable’, searches this in the list and when found returns its value as a string. When it fails, it returns NULL pointer.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Watch Advanced C Programming Videos
- Apply for C Internship
- Practice Computer Science MCQs
- Check C Books
- Apply for Computer Science Internship