]> diplodocus.org Git - nmh/blob - sbr/putenv.c
* I had alphabetized the --configure options in the --help output
[nmh] / sbr / putenv.c
1
2 /*
3 * putenv.c -- (un)set an envariable
4 *
5 * $Id$
6 */
7
8 #include <h/mh.h>
9
10 extern char **environ;
11
12 /*
13 * prototypes
14 */
15 int m_putenv (char *, char *);
16 int unputenv (char *);
17 static int nvmatch (char *, char *);
18
19
20 int
21 m_putenv (char *name, char *value)
22 {
23 register int i;
24 register char **ep, **nep, *cp;
25
26 if (!(cp = malloc ((size_t) (strlen (name) + strlen (value) + 2))))
27 return 1;
28
29 sprintf (cp, "%s=%s", name, value);
30
31 for (ep = environ, i = 0; *ep; ep++, i++)
32 if (nvmatch (name, *ep)) {
33 *ep = cp;
34 return 0;
35 }
36
37 if (!(nep = (char **) malloc ((size_t) ((i + 2) * sizeof(*nep)))))
38 return 1;
39
40 for (ep = environ, i = 0; *ep; nep[i++] = *ep++)
41 continue;
42 nep[i++] = cp;
43 nep[i] = NULL;
44 environ = nep;
45 return 0;
46 }
47
48
49 int
50 unputenv (char *name)
51 {
52 char **ep, **nep;
53
54 for (ep = environ; *ep; ep++)
55 if (nvmatch (name, *ep))
56 break;
57 if (*ep == NULL)
58 return 1;
59
60 for (nep = ep + 1; *nep; nep++)
61 continue;
62 *ep = *--nep;
63 *nep = NULL;
64 return 0;
65 }
66
67
68 static int
69 nvmatch (char *s1, char *s2)
70 {
71 while (*s1 == *s2++)
72 if (*s1++ == '=')
73 return 1;
74
75 return (*s1 == '\0' && *--s2 == '=');
76 }