strlcat.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* $OpenBSD: strlcat.c,v 1.10 2003/04/12 21:56:39 millert Exp $ */
  2. /*
  3. * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND TODD C. MILLER DISCLAIMS ALL
  10. * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
  11. * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER BE LIABLE
  12. * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  14. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  15. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include <sys/types.h>
  18. #include <string.h>
  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. }