-
Notifications
You must be signed in to change notification settings - Fork 0
/
setenv.c
93 lines (71 loc) · 2.13 KB
/
setenv.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/* setenv.c
An implementation of setenv() and unsetenv() using environ, putenv(),
and getenv().
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int
unsetenv(const char *name)
{
extern char **environ;
if (name == NULL || name[0] == '\0' || strchr(name, '=') != NULL) {
errno = EINVAL;
return -1;
}
size_t len = strlen(name);
for (char **ep = environ; *ep != NULL; )
if (strncmp(*ep, name, len) == 0 && (*ep)[len] == '=') {
/* Remove found entry by shifting all successive entries
back one element */
for (char **sp = ep; *sp != NULL; sp++)
*sp = *(sp + 1);
/* Continue around the loop to further instances of 'name' */
} else {
ep++;
}
return 0;
}
int
setenv(const char *name, const char *value, int overwrite)
{
if (name == NULL || name[0] == '\0' || strchr(name, '=') != NULL ||
value == NULL) {
errno = EINVAL;
return -1;
}
if (getenv(name) != NULL && overwrite == 0)
return 0;
unsetenv(name); /* Remove all occurrences */
char *es = malloc(strlen(name) + strlen(value) + 2);
/* +2 for '=' and null terminator */
if (es == NULL)
return -1;
strcpy(es, name);
strcat(es, "=");
strcat(es, value);
return (putenv(es) != 0) ? -1 : 0;
}
#ifdef TEST_IT
int
main()
{
if (putenv("TT=xxxxx") != 0)
perror("putenv");
system("echo '***** Environment before unsetenv(TT)'; "
"printenv | grep ^TT");
system("echo 'Total lines from printenv:' `printenv | wc -l`");
unsetenv("TT");
system("echo '***** Environment after unsetenv(TT)'; "
"printenv | grep ^TT");
system("echo 'Total lines from printenv:' `printenv | wc -l`");
setenv("xyz", "one", 1);
setenv("xyz", "two", 0);
setenv("xyz2", "222", 0);
system("echo '***** Environment after setenv() calls'; "
"printenv | grep ^x");
system("echo 'Total lines from printenv:' `printenv | wc -l`");
exit(EXIT_SUCCESS);
}
#endif