1 babf5d5a 2021-05-11 martijn /* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */
4 babf5d5a 2021-05-11 martijn * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
6 babf5d5a 2021-05-11 martijn * Permission to use, copy, modify, and distribute this software for any
7 babf5d5a 2021-05-11 martijn * purpose with or without fee is hereby granted, provided that the above
8 babf5d5a 2021-05-11 martijn * copyright notice and this permission notice appear in all copies.
10 babf5d5a 2021-05-11 martijn * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 babf5d5a 2021-05-11 martijn * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 babf5d5a 2021-05-11 martijn * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 babf5d5a 2021-05-11 martijn * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 babf5d5a 2021-05-11 martijn * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 babf5d5a 2021-05-11 martijn * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 babf5d5a 2021-05-11 martijn * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 babf5d5a 2021-05-11 martijn /* OPENBSD ORIGINAL: lib/libc/string/strlcpy.c */
21 babf5d5a 2021-05-11 martijn #include "openbsd-compat.h"
23 babf5d5a 2021-05-11 martijn #include <sys/types.h>
24 babf5d5a 2021-05-11 martijn #include <string.h>
27 babf5d5a 2021-05-11 martijn * Copy src to string dst of size siz. At most siz-1 characters
28 babf5d5a 2021-05-11 martijn * will be copied. Always NUL terminates (unless siz == 0).
29 babf5d5a 2021-05-11 martijn * Returns strlen(src); if retval >= siz, truncation occurred.
32 babf5d5a 2021-05-11 martijn strlcpy(char *dst, const char *src, size_t siz)
34 babf5d5a 2021-05-11 martijn char *d = dst;
35 babf5d5a 2021-05-11 martijn const char *s = src;
36 babf5d5a 2021-05-11 martijn size_t n = siz;
38 babf5d5a 2021-05-11 martijn /* Copy as many bytes as will fit */
39 babf5d5a 2021-05-11 martijn if (n != 0) {
40 babf5d5a 2021-05-11 martijn while (--n != 0) {
41 babf5d5a 2021-05-11 martijn if ((*d++ = *s++) == '\0')
46 babf5d5a 2021-05-11 martijn /* Not enough room in dst, add NUL and traverse rest of src */
47 babf5d5a 2021-05-11 martijn if (n == 0) {
48 babf5d5a 2021-05-11 martijn if (siz != 0)
49 babf5d5a 2021-05-11 martijn *d = '\0'; /* NUL-terminate dst */
50 babf5d5a 2021-05-11 martijn while (*s++)
54 babf5d5a 2021-05-11 martijn return(s - src - 1); /* count does not include NUL */