core: Add setenv.

* lib/libc.c (setenv): New function.
* include/stdlib.h (setenv): Declare it.
* scaffold/tests/61-array.c (test): Test it.
This commit is contained in:
Jan Nieuwenhuizen 2018-04-07 09:21:51 +02:00
parent 0fe6dc1f66
commit bd82d5988d
3 changed files with 39 additions and 9 deletions

View file

@ -39,6 +39,7 @@ void * calloc (size_t nmemb, size_t size);
void exit (int);
void free (void *ptr);
char* getenv (char const* s);
int settenv (char const* s, char const* v, int overwrite_p);
void *malloc (size_t);
void qsort (void *base, size_t nmemb, size_t size, int (*compar)(void const *, void const *));
void *realloc (void *p, size_t size);

View file

@ -320,6 +320,29 @@ getenv (char const* s)
return 0;
}
int
setenv (char const* s, char const* v, int overwrite_p)
{
char **p = g_environment;
int length = strlen (s);
while (*p)
{
if (!strncmp (s, *p, length) && *(*p + length) == '=')
break;
p++;
}
char *entry = malloc (length + strlen (v) + 2);
int end_p = *p == 0;
*p = entry;
strcpy (entry, s);
strcpy (entry + length, "=");
strcpy (entry + length + 1, v);
*(entry + length + strlen (v) + 2) = 0;
if (end_p)
*++p = 0;
return 0;
}
int
vprintf (char const* format, va_list ap)
{

View file

@ -46,10 +46,10 @@ test (char **e)
puts ("]\n");
puts ("env [0] == \"foo\"\n");
if (strcmp (env[0], "foo")) return 1;
if (strcmp (env[0], "foo")) return 2;
puts ("env [1] == \"bar\"\n");
if (strcmp (env[1], "bar")) return 1;
if (strcmp (env[1], "bar")) return 3;
puts ("t: **p in *env[]\n");
@ -68,27 +68,33 @@ test (char **e)
pp = env;
puts ("t: *pp++ == \"foo\"\n");
if (strcmp (*pp++, "foo")) return 1;
if (strcmp (*pp++, "foo")) return 4;
puts ("t: *pp++ == \"bar\"\n");
if (strcmp (*pp++, "bar")) return 1;
if (strcmp (*pp++, "bar")) return 5;
char *buf = "hello";
puts ("t: buf[0]\n");
if (buf[0] != 'h') return 1;
if (buf[0] != 'h') return 6;
puts ("t: buf + 1\n");
if (*(buf+1) != 'e') return 1;
if (*(buf+1) != 'e') return 7;
char **p = &buf;
puts ("t: **p\n");
if (**p != 'h') return 1;
if (**p != 'h') return 8;
puts ("t: *(p + 1)\n");
if (*(*p + 1) != 'e') return 1;
if (*(*p + 1) != 'e') return 9;
puts ("t: getenv ()");
if (!getenv ("PATH")) return 1;
if (!getenv ("PATH")) return 10;
puts ("t: setenv ()");
if (setenv ("61-array", "yes", 1)) return 11;
puts ("t: getenv2 ()");
if (strcmp (getenv ("61-array"), "yes")) return 12;
return 0;
}