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