home *** CD-ROM | disk | FTP | other *** search
/ ftp.ncftp.com / ftp.ncftp.com.zip / ftp.ncftp.com / libncftp / libncftp-3.2.5-src.zip / libncftp-3.2.5 / Strn / Strnpcpy.c < prev    next >
C/C++ Source or Header  |  2001-11-19  |  1KB  |  56 lines

  1. #include "syshdrs.h"
  2. #ifdef PRAGMA_HDRSTOP
  3. #    pragma hdrstop
  4. #endif
  5.  
  6. /*
  7.  * Copy src to dst, truncating or null-padding to always copy n-1 bytes.
  8.  *
  9.  * This routine differs from strncpy in that it returns a pointer to the end
  10.  * of the buffer, instead of strncat which returns a pointer to the start.
  11.  */
  12. char *
  13. Strnpcpy(char *const dst, const char *const src, size_t n)
  14. {
  15.     register char *d;
  16.     register const char *s;
  17.     register char c;
  18.     char *ret;
  19.     register size_t i;
  20.  
  21.     d = dst;
  22.     if (n != 0) {
  23.         s = src;
  24.         /* If they specified a maximum of n characters, use n - 1 chars to
  25.          * hold the copy, and the last character in the array as a NUL.
  26.          * This is the difference between the regular strncpy routine.
  27.          * strncpy doesn't guarantee that your new string will have a
  28.          * NUL terminator, but this routine does.
  29.          */
  30.         for (i=1; i<n; i++) {
  31.             c = *s++;
  32.             if (c == '\0') {
  33.                 ret = d;    /* Return ptr to end byte. */
  34.                 *d++ = c;
  35. #if (STRNP_ZERO_PAD == 1)
  36.                 /* Pad with zeros. */
  37.                 for (; i<n; i++)
  38.                     *d++ = 0;
  39. #endif    /* STRNP_ZERO_PAD */
  40.                 return ret;
  41.             }
  42.             *d++ = c;
  43.         }
  44.         /* If we get here, then we have a full string, with n - 1 characters,
  45.          * so now we NUL terminate it and go home.
  46.          */
  47.         *d = '\0';
  48.         return (d);    /* Return ptr to end byte. */
  49.     } else {
  50.         *d = 0;
  51.     }
  52.     return (d);    /* Return ptr to end byte. */
  53. }    /* Strnpcpy */
  54.  
  55. /* eof Strn.c */
  56.