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