strlcpy.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* strlcpy
  2. *
  3. */
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include "strlcpy.h"
  7. /*
  8. * Copy src to string dst of size siz. At most siz-1 characters
  9. * will be copied. Always NUL terminates (unless siz == 0).
  10. * Returns strlen(src); if retval >= siz, truncation occurred.
  11. */
  12. size_t
  13. strlcpy(char *dst, const char *src, size_t siz)
  14. {
  15. register char *d = dst;
  16. register const char *s = src;
  17. register size_t n = siz;
  18. /* Copy as many bytes as will fit */
  19. if (n != 0 && --n != 0) {
  20. do {
  21. if ((*d++ = *s++) == 0)
  22. break;
  23. } while (--n != 0);
  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. return (s - src - 1); /* count does not include NUL */
  32. }
  33. /*
  34. * Appends src to string dst of size siz (unlike strncat, siz is the
  35. * full size of dst, not space left). At most siz-1 characters
  36. * will be copied. Always NUL terminates (unless siz == 0).
  37. * Returns strlen(src); if retval >= siz, truncation occurred.
  38. */
  39. size_t
  40. strlcat(char *dst, const char *src, size_t siz)
  41. {
  42. register char *d = dst;
  43. register const char *s = src;
  44. register size_t n = siz;
  45. size_t dlen;
  46. /* Find the end of dst and adjust bytes left but don't go past end */
  47. while (*d != '\0' && n-- != 0)
  48. d++;
  49. dlen = d - dst;
  50. n = siz - dlen;
  51. if (n == 0)
  52. return (dlen + strlen(s));
  53. while (*s != '\0') {
  54. if (n != 1) {
  55. *d++ = *s;
  56. n--;
  57. }
  58. s++;
  59. }
  60. *d = '\0';
  61. return (dlen + (s - src)); /* count does not include NUL */
  62. }