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