*** empty log message ***
[bpt/guile.git] / libguile / putenv.c
CommitLineData
19468eff
GH
1/* Copyright (C) 1991 Free Software Foundation, Inc.
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2, or (at your option)
6 any later version.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
82892bed
JB
15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
16 USA */
19468eff
GH
17
18#ifdef HAVE_CONFIG_H
d183c1b9 19#include "libguile/scmconfig.h"
19468eff
GH
20#endif
21
22#include <sys/types.h>
23#include <errno.h>
24#ifndef errno
25extern int errno;
26#endif
27
28/* Don't include stdlib.h for non-GNU C libraries because some of them
29 contain conflicting prototypes for getopt.
30 This needs to come after some library #include
31 to get __GNU_LIBRARY__ defined. */
32#ifdef __GNU_LIBRARY__
33#include <stdlib.h>
34#else
35char *malloc ();
36#endif /* GNU C library. */
37
38#if defined(STDC_HEADERS) || defined(HAVE_STRING_H)
39#include <string.h>
40#else
41#include <strings.h>
42#ifndef strchr
43#define strchr index
44#endif
45#ifndef memcpy
46#define memcpy(d, s, n) bcopy((s), (d), (n))
47#endif
48#endif
49
50#ifdef HAVE_UNISTD_H
51#include <unistd.h>
52#endif
53
54#ifndef NULL
55#define NULL 0
56#endif
57
58extern char **environ;
59
60/* Put STRING, which is of the form "NAME=VALUE", in the environment. */
61int
62putenv (string)
63 const char *string;
64{
65 char *name_end = strchr (string, '=');
66 register size_t size;
67 register char **ep;
68
69 if (name_end == NULL)
70 {
71 /* Remove the variable from the environment. */
72 size = strlen (string);
73 for (ep = environ; *ep != NULL; ++ep)
74 if (!strncmp (*ep, string, size) && (*ep)[size] == '=')
75 {
76 while (ep[1] != NULL)
77 {
78 ep[0] = ep[1];
79 ++ep;
80 }
81 *ep = NULL;
82 return 0;
83 }
84 }
85
86 size = 0;
87 for (ep = environ; *ep != NULL; ++ep)
88 if (!strncmp (*ep, string, name_end - string) &&
89 (*ep)[name_end - string] == '=')
90 break;
91 else
92 ++size;
93
94 if (*ep == NULL)
95 {
96 static char **last_environ = NULL;
97 char **new_environ = (char **) malloc ((size + 2) * sizeof (char *));
98 if (new_environ == NULL)
99 return -1;
100 memcpy ((char *) new_environ, (char *) environ, size * sizeof (char *));
101 new_environ[size] = (char *) string;
102 new_environ[size + 1] = NULL;
103 if (last_environ != NULL)
104 free ((char *) last_environ);
105 last_environ = new_environ;
106 environ = new_environ;
107 }
108 else
109 *ep = (char *) string;
110
111 return 0;
112}