home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / zip / gnu / mntlib16.lzh / MNTLIB16 / GETENV.C < prev    next >
C/C++ Source or Header  |  1993-07-29  |  1KB  |  87 lines

  1. /* functions for manipulating the environment */
  2. /* written by Eric R. Smith and placed in the public domain */
  3.  
  4. #include <stddef.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7.  
  8. extern char ** environ;
  9.  
  10. char *
  11. getenv(tag)
  12.     const char *tag;
  13. {
  14.     char **var;
  15.     char *name;
  16.     size_t len = strlen(tag);
  17.  
  18.     if (!environ) return 0;
  19.  
  20.     for (var = environ; name = *var; var++) {
  21.         if (!strncmp(name, tag, len) && name[len] == '=')
  22.             return name+len+1;
  23.     }
  24.     return 0;
  25. }
  26.  
  27. static void
  28. del_env(strng)
  29.     const char *strng;
  30. {
  31.     char **var;
  32.     char *name;
  33.     size_t len = 0;
  34.  
  35.     if (!environ) return;
  36.  
  37. /* find the length of "tag" in "tag=value" */
  38.     for (name = (char *)strng; *name && (*name != '='); name++)
  39.         len++;
  40.  
  41. /* find the tag in the environment */
  42.     for (var = environ; name = *var; var++) {
  43.         if (!strncmp(name, strng, len) && name[len] == '=')
  44.             break;
  45.     }
  46.  
  47. /* if it's found, move all the other environment variables down by 1 to
  48.    delete it
  49.  */
  50.     if (name) {
  51.         while (name) {
  52.             name = var[1];
  53.             *var++ = name;
  54.         }
  55.     }
  56. }
  57.  
  58. int
  59. putenv(strng)
  60.     char *strng;
  61. {
  62.     int i = 0;
  63.     char **e;
  64.  
  65.     del_env(strng);
  66.  
  67.     if (!environ)
  68.         e = malloc(2*sizeof(char *));
  69.     else {
  70.         while(environ[i]) i++ ;
  71.         e = malloc((i+2)*sizeof(char *));
  72.         if (!e) {
  73.             return -1;
  74.         }
  75.         bcopy(environ, e, (i+1)*sizeof(char *));
  76.         free(environ);
  77.         environ = e;
  78.     }
  79.     if (!e)
  80.         return -1;
  81.  
  82.     environ = e;
  83.     environ[i] = strng;
  84.     environ[i+1] = 0;
  85.     return 0;
  86. }
  87.