strlcpy.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* $OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp $ */
  2. /*
  3. * SPDX-License-Identifier: ISC
  4. *
  5. * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
  6. *
  7. * Permission to use, copy, modify, and distribute this software for any
  8. * purpose with or without fee is hereby granted, provided that the above
  9. * copyright notice and this permission notice appear in all copies.
  10. *
  11. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  12. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  13. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  14. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  15. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  16. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  17. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  18. */
  19. #include <stdint.h>
  20. #include <string.h>
  21. /*
  22. * Copy string src to buffer dst of size dsize. At most dsize-1
  23. * chars will be copied. Always NUL terminates (unless dsize == 0).
  24. * Returns strlen(src); if retval >= dsize, truncation occurred.
  25. */
  26. size_t
  27. strlcpy(char * dst, const char * src, size_t dsize)
  28. {
  29. const char *osrc = src;
  30. size_t nleft = dsize;
  31. /* Copy as many bytes as will fit. */
  32. if (nleft != 0) {
  33. while (--nleft != 0) {
  34. if ((*dst++ = *src++) == '\0')
  35. break;
  36. }
  37. }
  38. /* Not enough room in dst, add NUL and traverse rest of src. */
  39. if (nleft == 0) {
  40. if (dsize != 0)
  41. *dst = '\0'; /* NUL-terminate dst */
  42. while (*src++)
  43. ;
  44. }
  45. return(src - osrc - 1); /* count does not include NUL */
  46. }