diff --git a/include/stdlib.h b/include/stdlib.h index 651fb0ee..3bf99a53 100644 --- a/include/stdlib.h +++ b/include/stdlib.h @@ -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); diff --git a/lib/libc.c b/lib/libc.c index 384af166..836800ca 100644 --- a/lib/libc.c +++ b/lib/libc.c @@ -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) { diff --git a/scaffold/tests/61-array.c b/scaffold/tests/61-array.c index 0239f02d..376a6a41 100644 --- a/scaffold/tests/61-array.c +++ b/scaffold/tests/61-array.c @@ -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; }