home *** CD-ROM | disk | FTP | other *** search
/ Power Programming / powerprogramming1994.iso / progtool / c / string.arc / SUBSTR.C < prev    next >
C/C++ Source or Header  |  1984-12-31  |  2KB  |  57 lines

  1. /*  File   : substr.c
  2.     Author : Richard A. O'Keefe.
  3.     Updated: 25 May 1984
  4.     Defines: substr()
  5.  
  6.     substr(destination, source, offset, length)
  7.     copies length bytes from source+offset to destination, stopping
  8.     early if a NUL is encountered.  The difference between this and
  9.     strncpy(destination, source+offset, length)
  10.     is that if the offset is negative, it has the same effect as 0,
  11.     and if it exceeds strlen(source), it has the same effect as
  12.     strlen(source).  If either of these boundaries is hit, or if
  13.     a NUL is encountered before length bytes have been moved, the
  14.     value of errno will be EDOM, otherwise it is guaranteed to be 0.
  15.     That is:
  16.     errno == 0 <=> (0 <= offset <= strlen(source)
  17.             && 0 <= length && <= strlen(source)-offset)
  18.     You may accept the sensible result produced when these boundary
  19.     conditions are violated, or you may treat it as an error, as you
  20.     will.  There is an algebra of sequences in which this treatment
  21.     of boundary conditions makes sense.
  22.  
  23.     After the substring of source is moved to destination, a NUL byte
  24.     is moved to terminate the string, and the result is a pointer to
  25.     this NUL byte, ready to have new stuff stuck on the end.
  26.  
  27.     I suppose this should be called strsub, but I can't stick it.
  28. */
  29.  
  30. #include "strings.h"
  31. #include <errno.h>
  32.  
  33. extern    int    errno;            /* why isn't this in errno.h?? */
  34.  
  35.  
  36. char *substr(dst, src, off, len)
  37.     register char *dst, *src;
  38.     register int off, len;
  39.     {
  40.     errno = off < 0 || len < 0 ? EDOM : 0;
  41.  
  42.     while (--off >= 0)
  43.         if (!*src++) {        /* We've hit the end */
  44.         errno = EDOM;        /* report boundary violation */
  45.         *dst = NUL;        /* return empty string */
  46.         return dst;
  47.         }
  48.     while (--len >= 0)
  49.         if (!(*dst++ = *src++)) {    /* We've hit the end */
  50.         errno = EDOM;
  51.         return dst-1;        /* dst is already terminated */
  52.         }
  53.     *dst = NUL;            /* terminate dst with NUL */
  54.     return dst;
  55.     }
  56.