strlcat.c (2005B)
1 /* 2 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> 3 * 4 * Permission to use, copy, modify, and distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 #include "pkg.h" 18 19 /* 20 * Appends src to string dst of size siz (unlike strncat, siz is the 21 * full size of dst, not space left). At most siz-1 characters 22 * will be copied. Always NUL terminates (unless siz <= strlen(dst)). 23 * Returns strlen(src) + MIN(siz, strlen(initial dst)). 24 * If retval >= siz, truncation occurred. 25 */ 26 size_t 27 strlcat(char *dst, const char *src, size_t siz) 28 { 29 char *d = dst; 30 const char *s = src; 31 size_t n = siz; 32 size_t dlen; 33 /* Find the end of dst and adjust bytes left but don't go past end */ 34 while (n-- != 0 && *d != '\0') 35 d++; 36 dlen = d - dst; 37 n = siz - dlen; 38 if (n == 0) 39 return(dlen + strlen(s)); 40 while (*s != '\0') { 41 if (n != 1) { 42 *d++ = *s; 43 n--; 44 } 45 s++; 46 } 47 *d = '\0'; 48 return(dlen + (s - src)); /* count does not include NUL */ 49 } 50 51 size_t 52 estrlcat(char *dst, const char *src, size_t siz) 53 { 54 size_t r; 55 56 r = strlcat(dst, src, siz); 57 if (r >= siz) { 58 fprintf(stderr, "destination buffer too small\n"); 59 exit(EXIT_FAILURE); 60 } 61 return r; 62 }