gtpc2m6c | C/C++ Language Support User's Guide |
This function adds, changes, or deletes environment variables.
Format
#define _POSIX_SOURCE #include <stdlib.h> int setenv(const char *var_name, const char *new_value, int change_flag)
If var_name is already defined and exists in the environment list, change the existing entry to new_value.
If var_name was previously undefined, it is added to the environment list.
If var_name is defined and exists in the environment list, the value is not changed to new_value.
If var_name was previously undefined, it is added to the environment list.
Normal Return
0
Error Return
-1 and sets errno to one of the following:
Programming Considerations
Examples
The following example sets up and prints the value of the environment variable _EDC_ANSI_OPEN_DEFAULT.
#include <stdio.h> #define _POSIX_SOURCE #include <stdlib.h> int main(void) { char *x; /* set environment variable _EDC_ANSI_OPEN_DEFAULT to "Y" */ setenv("_EDC_ANSI_OPEN_DEFAULT","Y",1); /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/ x = getenv("_EDC_ANSI_OPEN_DEFAULT"); printf("program1 _EDC_ANSI_OPEN_DEFAULT = %s\n", (x != NULL) ? x : "undefined"); /* call the child program */ system("program2"); /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/ x = getenv("_EDC_ANSI_OPEN_DEFAULT"); printf("program1 _EDC_ANSI_OPEN_DEFAULT = %s\n", (x != NULL) ? x : "undefined"); }
Output
program1 _EDC_ANSI_OPEN_DEFAULT = Y program1 _EDC_ANSI_OPEN_DEFAULT = Y
In the following example, a child ECB of the previous example was started by a system call. Like the previous example, this example sets up and prints the value of the environment variable _EDC_ANSI_OPEN_DEFAULT. The program then deletes the environment value and prints the value as undefined. This example shows that environment variables are propagated forward to a child ECB, but not backward to the parent ECB.
#include <stdio.h> #include <stdlib.h> int main(void) { char *x; /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/ x = getenv("_EDC_ANSI_OPEN_DEFAULT"); printf("program2 _EDC_ANSI_OPEN_DEFAULT = %s\n", (x != NULL) ? x : "undefined"); /* clear the Environment Variables Table */ unsetenv("_EDC_ANSI_OPEN_DEFAULT"); /* set x to the current value of the _EDC_ANSI_OPEN_DEFAULT*/ x = getenv("_EDC_ANSI_OPEN_DEFAULT"); printf("program2 _EDC_ANSI_OPEN_DEFAULT = %s\n", (x != NULL) ? x : "undefined"); }
Output
program2 _EDC_ANSI_OPEN_DEFAULT = Y program2 _EDC_ANSI_OPEN_DEFAULT = undefined
Related Information