home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume16 / pcomm2 / part06 / strings.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-09-14  |  1.3 KB  |  78 lines

  1. /*
  2.  * Miscellaneous string routines.
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. /*
  8.  * Do a fancy string copy.  If NULL, return null.  If pointer to NULL, then
  9.  * return the special "null_ptr" variable.  If a normal copy, allocate
  10.  * memory first.
  11.  */
  12.  
  13. char *
  14. strdup(str)
  15. char *str;
  16. {
  17.     extern char *null_ptr;
  18.     char *ret, *malloc(), *strcpy();
  19.  
  20.     if (str == NULL)
  21.         return(NULL);
  22.                     /* if pointer to null */
  23.     if (*str == NULL)
  24.         return(null_ptr);
  25.  
  26.     ret = malloc((unsigned int) strlen(str)+1);
  27.     strcpy(ret, str);
  28.     return(ret);
  29. }
  30.  
  31. /*
  32.  * Perform the free(2) function, but check for NULL and the special
  33.  * "null_ptr" variable first.
  34.  */
  35.  
  36. void
  37. free_ptr(str)
  38. char *str;
  39. {
  40.     extern char *null_ptr;
  41.     void free();
  42.  
  43.     if (str != NULL && str != null_ptr)
  44.         free(str);
  45.     return;
  46. }
  47.  
  48. /*
  49.  * This routine is similar to strtok(3).  But our version handles null
  50.  * strings and takes a single separator character as an argument.
  51.  * Returns a NULL on end of string or error.
  52.  */
  53.  
  54. char *
  55. str_tok(str, c)
  56. char *str, c;
  57. {
  58.     extern char *null_ptr;
  59.     char *strchr();
  60.     static char *ptr, *sep;
  61.                     /* start at beginning */
  62.     if (str != NULL)
  63.         ptr = str;
  64.     else
  65.         ptr = sep;
  66.                     /* at the end? */
  67.     if (*ptr == NULL)
  68.         return(NULL);
  69.                     /* no separator? */
  70.     if (!(sep = strchr(ptr, c)))
  71.         return(NULL);
  72.                     /* zap the sep, move past it */
  73.     *sep = NULL;
  74.     sep++;
  75.  
  76.     return(ptr);
  77. }
  78.