setenv.c 504 B

12345678910111213141516171819202122232425262728293031
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <errno.h>
  4. int __putenv(char *s, int a);
  5. int setenv(const char *var, const char *value, int overwrite)
  6. {
  7. char *s;
  8. int l1, l2;
  9. if (strchr(var, '=')) {
  10. errno = EINVAL;
  11. return -1;
  12. }
  13. if (!overwrite && getenv(var)) return 0;
  14. l1 = strlen(var);
  15. l2 = strlen(value);
  16. s = malloc(l1+l2+2);
  17. memcpy(s, var, l1);
  18. s[l1] = '=';
  19. memcpy(s+l1+1, value, l2);
  20. s[l1+l2+1] = 0;
  21. if (__putenv(s, 1)) {
  22. free(s);
  23. errno = ENOMEM;
  24. return -1;
  25. }
  26. return 0;
  27. }