00001 /* $NetBSD: strlcpy.c,v 1.14 2003/10/27 00:12:42 lukem Exp $ */ 00002 /* $OpenBSD: strlcpy.c,v 1.7 2003/04/12 21:56:39 millert Exp $ */ 00003 00004 /* 00005 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> 00006 * 00007 * Permission to use, copy, modify, and distribute this software for any 00008 * purpose with or without fee is hereby granted, provided that the above 00009 * copyright notice and this permission notice appear in all copies. 00010 * 00011 * THE SOFTWARE IS PROVIDED "AS IS" AND TODD C. MILLER DISCLAIMS ALL 00012 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES 00013 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER BE LIABLE 00014 * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 00015 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION 00016 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 00017 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 00018 */ 00019 #include <u/libu_conf.h> 00020 #include <sys/types.h> 00021 #include <string.h> 00022 00023 #ifndef HAVE_STRLCPY 00024 /* 00025 * Copy src to string dst of size siz. At most siz-1 characters 00026 * will be copied. Always NUL terminates (unless siz == 0). 00027 * Returns strlen(src); if retval >= siz, truncation occurred. 00028 */ 00029 size_t 00030 strlcpy(dst, src, siz) 00031 char *dst; 00032 const char *src; 00033 size_t siz; 00034 { 00035 char *d = dst; 00036 const char *s = src; 00037 size_t n = siz; 00038 00039 /* Copy as many bytes as will fit */ 00040 if (n != 0 && --n != 0) { 00041 do { 00042 if ((*d++ = *s++) == 0) 00043 break; 00044 } while (--n != 0); 00045 } 00046 00047 /* Not enough room in dst, add NUL and traverse rest of src */ 00048 if (n == 0) { 00049 if (siz != 0) 00050 *d = '\0'; /* NUL-terminate dst */ 00051 while (*s++) 00052 ; 00053 } 00054 00055 return(s - src - 1); /* count does not include NUL */ 00056 } 00057 #else 00058 size_t strlcpy(char *, const char *, size_t); 00059 #endif