Last active
December 14, 2015 16:58
-
-
Save chaitanyav/5118436 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Author: NagaChaitanya Vellanki | |
* | |
* | |
* get or set or unset environment variables | |
* clean environment | |
* gcc -o get_set_env -Wall --pedantic get_set_env.c -D_SVID_SOURCE | |
*/ | |
#include<stdio.h> | |
#include<stdlib.h> | |
#include<errno.h> | |
#include<string.h> | |
extern char **environ; | |
int main(int argc, char *argv[]) { | |
char env_name1[] = "SHELL"; | |
char env_name2[] = "FOO"; | |
char env_foo[] = "FOO=BAR"; | |
fprintf(stdout, "%s=%s\n", env_name1, getenv(env_name1)); | |
fprintf(stdout, "%s=%s\n", env_name2, getenv(env_name2)); | |
if(putenv(env_foo)) { | |
fprintf(stderr, "Error while setting the env variable FOO, %s\n", strerror(errno)); | |
exit(EXIT_FAILURE); | |
} | |
fprintf(stdout, "%s=%s\n", env_name2, getenv(env_name2)); | |
if(setenv("FOO", "GOO", 0) == -1) { | |
fprintf(stderr, "Error while setting the env variable FOO, %s\n", strerror(errno)); | |
exit(EXIT_FAILURE); | |
} | |
fprintf(stdout, "%s=%s\n", env_name2, getenv(env_name2)); | |
if(setenv("FOO", "GOO", 1) == -1) { | |
fprintf(stderr, "Error while setting the env variable FOO, %s\n", strerror(errno)); | |
exit(EXIT_FAILURE); | |
} | |
fprintf(stdout, "%s=%s\n", env_name2, getenv(env_name2)); | |
if(unsetenv("FOO") == -1) { | |
fprintf(stderr, "Error while unsetting the env variable FOO, %s\n", strerror(errno)); | |
exit(EXIT_FAILURE); | |
} | |
fprintf(stdout, "%s=%s\n", env_name2, getenv(env_name2)); | |
if(clearenv()) { | |
fprintf(stderr, "Error while clearing the environment variables, %s\n", strerror(errno)); | |
exit(EXIT_FAILURE); | |
} | |
fprintf(stdout, "%s=%s\n", env_name1, getenv(env_name1)); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment