strlcpy.c 713 B

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