setenv.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Copyright (C) 1995,1996 Robert de Bath <rdebath@cix.compulink.co.uk>
  2. * This file is part of the Linux-8086 C library and is distributed
  3. * under the GNU Library General Public License.
  4. */
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <malloc.h>
  8. extern char ** environ;
  9. #define ADD_NUM 4
  10. int
  11. setenv(var, value, overwrite)
  12. const char * var;
  13. const char * value;
  14. int overwrite;
  15. {
  16. static char ** mall_env = 0;
  17. static int extras = 0;
  18. char **p, **d;
  19. char * t;
  20. int len;
  21. len = strlen(var);
  22. if (!environ) {
  23. environ = (char**)malloc(ADD_NUM * sizeof(char*));
  24. memset(environ, 0, sizeof(char*)*ADD_NUM);
  25. extras = ADD_NUM;
  26. }
  27. for(p=environ; *p; p++)
  28. {
  29. if( memcmp(var, *p, len) == 0 && (*p)[len] == '=' )
  30. {
  31. if (!overwrite)
  32. return -1;
  33. /* Overwrite stuff */
  34. while( (p[0] = p[1]) ) p++;
  35. extras++;
  36. break;
  37. }
  38. }
  39. if( extras <= 0 ) /* Need more space */
  40. {
  41. d = malloc((p-environ+1+ADD_NUM)*sizeof(char*));
  42. if( d == 0 ) return -1;
  43. memcpy((void*) d, (void*) environ, (p-environ+1)*sizeof(char*));
  44. p = d + (p-environ);
  45. extras=ADD_NUM;
  46. if( mall_env ) free(mall_env);
  47. environ = d;
  48. mall_env = d;
  49. }
  50. t = malloc(len + 1 + strlen(value) + 1);
  51. if (!t)
  52. return -1;
  53. strcpy(t, var);
  54. strcat(t, "=");
  55. strcat(t, value);
  56. *p++ = (char*)t;
  57. *p = '\0';
  58. extras--;
  59. return 0;
  60. }