util.c (770B)
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <sys/types.h> 5 6 #include "util.h" 7 8 /* 9 * Taken from OpenBSD. 10 * Copy src to string dst of size siz. At most siz-1 characters 11 * will be copied. Always NUL terminates (unless siz == 0). 12 * Returns strlen(src); if retval >= siz, truncation occurred. 13 */ 14 size_t 15 strlcpy(char *dst, const char *src, size_t siz) { 16 char *d = dst; 17 const char *s = src; 18 size_t n = siz; 19 20 /* copy as many bytes as will fit */ 21 if (n != 0) { 22 while (--n != 0) { 23 if ((*d++ = *s++) == '\0') 24 break; 25 } 26 } 27 /* not enough room in dst, add NUL and traverse rest of src */ 28 if (n == 0) { 29 if (siz != 0) 30 *d = '\0'; /* NUL-terminate dst */ 31 while (*s++) 32 ; 33 } 34 return(s - src - 1); /* count does not include NUL */ 35 }