putenv.c (632B)
1 #include <errno.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 extern char **_environ; 6 7 int 8 putenv(char *name) 9 { 10 char **p, *s; 11 size_t siz, len, cnt; 12 static char **lastenv; 13 14 if ((s = strchr(name, '=')) == NULL) { 15 errno = EINVAL; 16 return -1; 17 } 18 len = s - name; 19 20 for (p = _environ; *p; ++p) { 21 if (!strncmp(name, *p, len) && (*p)[len] == '=') { 22 *p = name; 23 return 0; 24 } 25 } 26 27 cnt = p - _environ; 28 siz = (cnt + 2) * sizeof(char **); 29 30 if ((p = realloc(lastenv, siz)) == NULL) 31 return -1; 32 if (!lastenv) 33 memcpy(p, _environ, cnt * sizeof(char **)); 34 lastenv = _environ = p; 35 36 p[cnt] = name; 37 p[cnt+1] = NULL; 38 39 return 0; 40 }