putenv.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*!
  2. \file lib/gis/putenv.c
  3. \brief GIS library - environment routines
  4. (C) 2001-2009, 2011 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. \author Original author CERL
  8. \author Updated for GRASS7 by Glynn Clements
  9. */
  10. #include <string.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <grass/config.h>
  14. #include <grass/gis.h>
  15. #if !defined(HAVE_PUTENV) && !defined(HAVE_SETENV)
  16. extern char **environ;
  17. #endif
  18. /*!
  19. \brief Sets the UNIX environment variable name to value
  20. \param name env name
  21. \param value env value
  22. */
  23. void G_putenv(const char *name, const char *value)
  24. {
  25. char buf[1024];
  26. #if defined(HAVE_PUTENV)
  27. sprintf(buf, "%s=%s", name, value);
  28. putenv(G_store(buf));
  29. #elif defined(HAVE_SETENV)
  30. setenv(name, value, 1);
  31. #else
  32. static int first = 1;
  33. int i;
  34. char **newenv;
  35. char *env;
  36. if (first) {
  37. for (i = 0; environ[i]; i++) ;
  38. newenv = (char **)G_malloc((i + 1) * sizeof(char *));
  39. for (i = 0; env = environ[i], env; i++)
  40. newenv[i] = G_store(env);
  41. newenv[i] = NULL;
  42. environ = newenv;
  43. first = 0;
  44. }
  45. for (i = 0; env = environ[i], env; i++) {
  46. char temp[4];
  47. if (sscanf(env, "%[^=]=%1s", buf, temp) < 1)
  48. continue;
  49. if (strcmp(buf, name) != 0)
  50. continue;
  51. G_free(env);
  52. sprintf(buf, "%s=%s", name, value);
  53. environ[i] = G_store(buf);
  54. return;
  55. }
  56. environ = (char **)G_realloc(environ, (i + 2) * sizeof(char *));
  57. sprintf(buf, "%s=%s", name, value);
  58. environ[i++] = G_store(buf);
  59. environ[i] = NULL;
  60. #endif
  61. }