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