1184059Sdelphij/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */ 249593Simp 349593Simp/* 449593Simp * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> 549593Simp * 6184059Sdelphij * Permission to use, copy, modify, and distribute this software for any 7184059Sdelphij * purpose with or without fee is hereby granted, provided that the above 8184059Sdelphij * copyright notice and this permission notice appear in all copies. 949593Simp * 10184059Sdelphij * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11184059Sdelphij * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12184059Sdelphij * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13184059Sdelphij * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14184059Sdelphij * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15184059Sdelphij * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16184059Sdelphij * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 1749593Simp */ 1849593Simp 1986170Sobrien#include <sys/cdefs.h> 2086170Sobrien__FBSDID("$FreeBSD$"); 2149593Simp 2249593Simp#include <sys/types.h> 2349593Simp#include <string.h> 2449593Simp 2549593Simp/* 2649593Simp * Copy src to string dst of size siz. At most siz-1 characters 2749593Simp * will be copied. Always NUL terminates (unless siz == 0). 2849593Simp * Returns strlen(src); if retval >= siz, truncation occurred. 2949593Simp */ 30159644Smaximsize_t 31189133Sdasstrlcpy(char * __restrict dst, const char * __restrict src, size_t siz) 3249593Simp{ 3392889Sobrien char *d = dst; 3492889Sobrien const char *s = src; 3592889Sobrien size_t n = siz; 3649593Simp 3749594Simp /* Copy as many bytes as will fit */ 38184059Sdelphij if (n != 0) { 39184059Sdelphij while (--n != 0) { 40184059Sdelphij if ((*d++ = *s++) == '\0') 4149594Simp break; 42184059Sdelphij } 4349593Simp } 4449593Simp 4549594Simp /* Not enough room in dst, add NUL and traverse rest of src */ 4649594Simp if (n == 0) { 4749594Simp if (siz != 0) 4849594Simp *d = '\0'; /* NUL-terminate dst */ 4949594Simp while (*s++) 5049594Simp ; 5149594Simp } 5249594Simp 5349594Simp return(s - src - 1); /* count does not include NUL */ 5449593Simp} 55