]> diplodocus.org Git - nmh/blob - docs/historical/mh-jun-1982/subs/putenv.c
Create new mh-format function %(ordinal)
[nmh] / docs / historical / mh-jun-1982 / subs / putenv.c
1 #ifdef COMMENT
2 Proprietary Rand Corporation, 1981.
3 Further distribution of this software
4 subject to the terms of the Rand
5 license agreement.
6 #endif
7
8 /*
9 * putenv(name, arg)
10 * replaces or adds the `name' entry with "name=arg";
11 *
12 * Uses malloc() for space for new vector and new entry;
13 *
14 * Bruce Borden January 1980
15 * The Rand Corporation
16 */
17
18 #include <stdio.h>
19
20 extern char **environ;
21
22 putenv(name, arg)
23 char *name, *arg;
24 {
25 register int i;
26 register char **ep, **nep, *cp;
27
28 if((cp = (char *) malloc(strlen(name) + strlen(arg) + 2)) == NULL)
29 return(1);
30 strcpy(cp, name);
31 strcat(cp, "=");
32 strcat(cp, arg);
33 for(ep = environ, i = 0; *ep; ep++, i++)
34 if(nvmatch(name, *ep)) {
35 *ep = cp;
36 return(0);
37 }
38 if((nep = (char **) malloc((i+2) * sizeof *nep)) == NULL)
39 return(1);
40 for(ep = environ, i = 0; *ep; )
41 nep[i++] = *ep++;
42 nep[i++] = cp;
43 nep[i] = 0;
44 environ = nep;
45 return(0);
46 }
47
48 /*
49 * s1 is either name, or name=value
50 * s2 is name=value
51 * if names match, return value of s2, else NULL
52 * used for environment searching: see getenv
53 */
54
55 static
56 nvmatch(s1, s2)
57 register char *s1, *s2;
58 {
59
60 while (*s1 == *s2++)
61 if (*s1++ == '=')
62 return(1);
63 if (*s1 == '\0' && *(s2-1) == '=')
64 return(1);
65 return(0);
66 }