/contrib/groff/src/libs/libgroff/putenv.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 99 lines · 66 code · 13 blank · 20 comment · 20 complexity · fd2fdd2baaa0832a5db20166b149de35 MD5 · raw file

  1. /* Copyright (C) 1991, 2001 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Library General Public License as
  5. published by the Free Software Foundation; either version 2 of the
  6. License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Library General Public License for more details.
  11. You should have received a copy of the GNU Library General Public
  12. License along with the GNU C Library; see the file COPYING.LIB. If
  13. not, write to the Free Software Foundation, Inc., 675 Mass Ave,
  14. Cambridge, MA 02139, USA. */
  15. /* Hacked slightly by jjc@jclark.com for groff. */
  16. #ifdef HAVE_CONFIG_H
  17. #include <config.h>
  18. #endif
  19. #include <string.h>
  20. #ifdef __STDC__
  21. #include <stddef.h>
  22. typedef void *PTR;
  23. typedef size_t SIZE_T;
  24. #else /* not __STDC__ */
  25. typedef char *PTR;
  26. typedef int SIZE_T;
  27. #endif /* not __STDC__ */
  28. #ifdef HAVE_STDLIB_H
  29. #include <stdlib.h>
  30. #else /* not HAVE_STDLIB_H */
  31. PTR malloc();
  32. #endif /* not HAVE_STDLIB_H */
  33. #ifndef NULL
  34. #define NULL 0
  35. #endif
  36. extern char **environ;
  37. /* Put STRING, which is of the form "NAME=VALUE", in the environment. */
  38. int putenv(const char *string)
  39. {
  40. char *name_end = strchr(string, '=');
  41. SIZE_T size;
  42. char **ep;
  43. if (name_end == NULL)
  44. {
  45. /* Remove the variable from the environment. */
  46. size = strlen(string);
  47. for (ep = environ; *ep != NULL; ++ep)
  48. if (!strncmp(*ep, string, size) && (*ep)[size] == '=')
  49. {
  50. while (ep[1] != NULL)
  51. {
  52. ep[0] = ep[1];
  53. ++ep;
  54. }
  55. *ep = NULL;
  56. return 0;
  57. }
  58. }
  59. size = 0;
  60. for (ep = environ; *ep != NULL; ++ep)
  61. if (!strncmp(*ep, string, name_end - string)
  62. && (*ep)[name_end - string] == '=')
  63. break;
  64. else
  65. ++size;
  66. if (*ep == NULL)
  67. {
  68. static char **last_environ = NULL;
  69. char **new_environ = (char **) malloc((size + 2) * sizeof(char *));
  70. if (new_environ == NULL)
  71. return -1;
  72. (void) memcpy((PTR) new_environ, (PTR) environ, size * sizeof(char *));
  73. new_environ[size] = (char *) string;
  74. new_environ[size + 1] = NULL;
  75. if (last_environ != NULL)
  76. free((PTR) last_environ);
  77. last_environ = new_environ;
  78. environ = new_environ;
  79. }
  80. else
  81. *ep = (char *) string;
  82. return 0;
  83. }