ack/lang/cem/libcc.ansi/core/stdlib/putenv.c

89 lines
1.5 KiB
C
Raw Normal View History

1990-01-03 17:23:10 +00:00
/*
* (c) copyright 1989 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*/
1994-06-24 14:02:31 +00:00
/* $Id$ */
1990-01-03 17:23:10 +00:00
2018-06-21 20:33:47 +00:00
#include <stdlib.h>
#include <string.h>
1990-01-03 17:23:10 +00:00
2018-06-21 20:33:47 +00:00
#define ENTRY_INC 10
#define rounded(x) (((x / ENTRY_INC) + 1) * ENTRY_INC)
1990-01-03 17:23:10 +00:00
2018-06-21 20:33:47 +00:00
extern char** environ;
1990-01-03 17:23:10 +00:00
2018-06-21 20:33:47 +00:00
int putenv(char* name)
1990-01-03 17:23:10 +00:00
{
2018-06-21 20:33:47 +00:00
register char** v = environ;
register char* r;
1990-01-03 17:23:10 +00:00
static int size = 0;
/* When size != 0, it contains the number of entries in the
* table (including the final NULL pointer). This means that the
* last non-null entry is environ[size - 2].
1990-01-03 17:23:10 +00:00
*/
2018-06-21 20:33:47 +00:00
if (!name)
return 0;
if (r = strchr(name, '='))
{
1990-01-03 17:23:10 +00:00
register const char *p, *q;
*r = '\0';
2018-06-21 20:33:47 +00:00
if (v != NULL)
{
while ((p = *v) != NULL)
{
1990-01-03 17:23:10 +00:00
q = name;
while (*q && (*q++ == *p++))
2018-06-21 20:33:47 +00:00
/* EMPTY */;
if (*q || (*p != '='))
{
1990-01-03 17:23:10 +00:00
v++;
2018-06-21 20:33:47 +00:00
}
else
{
1990-01-03 17:23:10 +00:00
/* The name was already in the
* environment.
*/
*r = '=';
*v = name;
return 0;
}
}
}
*r = '=';
v = environ;
1990-01-03 17:23:10 +00:00
}
2018-06-21 20:33:47 +00:00
if (!size)
{
register char** p;
1990-01-03 17:23:10 +00:00
register int i = 0;
if (v)
2018-06-21 20:33:47 +00:00
do
{
1990-01-03 17:23:10 +00:00
i++;
} while (*v++);
2018-06-21 20:33:47 +00:00
if (!(v = malloc(rounded(i) * sizeof(char**))))
1990-01-03 17:23:10 +00:00
return 1;
size = i;
p = environ;
environ = v;
2018-06-21 20:33:47 +00:00
while (*v++ = *p++)
; /* copy the environment */
v = environ;
2018-06-21 20:33:47 +00:00
}
else if (!(size % ENTRY_INC))
{
if (!(v = realloc(environ, rounded(size) * sizeof(char**))))
1990-01-03 17:23:10 +00:00
return 1;
environ = v;
1990-01-03 17:23:10 +00:00
}
v[size - 1] = name;
v[size] = NULL;
size++;
return 0;
}