Added all of the MH sources, including RCS files, in
[mmh] / docs / historical / mh-6.8.5 / sbr / putenv.c
1 /* putenv.c - (un) set an envariable */
2 #ifndef lint
3 static char ident[] = "@(#)$Id: putenv.c,v 1.6 1992/12/15 00:20:22 jromine Exp $";
4 #endif  /* lint */
5
6 #include "../h/mh.h"
7 #include <stdio.h>
8
9
10 extern  char **environ;
11
12 static nvmatch();
13
14 int     m_putenv (name, value)
15 register char  *name,
16                *value;
17 {
18     register int    i;
19     register char **ep,
20                   **nep,
21                    *cp;
22
23     if ((cp = malloc ((unsigned) (strlen (name) + strlen (value) + 2)))
24             == NULL)
25         return 1;
26     (void) sprintf (cp, "%s=%s", name, value);
27
28     for (ep = environ, i = 0; *ep; ep++, i++)
29         if (nvmatch (name, *ep)) {
30             *ep = cp;
31             return 0;
32         }
33
34     if ((nep = (char **) malloc ((unsigned) ((i + 2) * sizeof *nep))) == NULL)
35         return 1;
36     for (ep = environ, i = 0; *ep; nep[i++] = *ep++)
37         continue;
38     nep[i++] = cp;
39     nep[i] = NULL;
40     environ = nep;
41     return 0;
42 }
43
44
45 int     unputenv (name)
46 char   *name;
47 {
48     char  **ep,
49           **nep;
50
51     for (ep = environ; *ep; ep++)
52         if (nvmatch (name, *ep))
53             break;
54     if (*ep == NULL)
55         return 1;
56
57     for (nep = ep + 1; *nep; nep++)
58         continue;
59     *ep = *--nep;
60     *nep = NULL;
61     return 0;
62 }
63
64 /* \f */
65
66 static nvmatch (s1, s2)
67 register char  *s1,
68                *s2;
69 {
70     while (*s1 == *s2++)
71         if (*s1++ == '=')
72             return 1;
73
74     return (*s1 == '\0' && *--s2 == '=');
75 }