|
|
#include <string.h>size_t strlcpy(char *dst, const char *src, size_t size)
size_t strlcat(char *dst, const char *src, size_t size)
The strlcpy( ) function copies up to size-1 characters from the NUL terminated string, src, to dst, NUL terminating the result.
The strlcat( ) function appends the NULL terminated string src to the end of dst. It will append at most size-strlen(dst)-1 bytes, NUL terminating the result.
See Todd C. Miller, Consistant Safe strcpy and catenation, Freenix track:1999 USENIX Annual Technical Conference. Also ftp::/ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcat.c.
char *s, *p, buf[BUFSIZ];To detect truncation, perhaps while building a pathname, use code like the following:...
(void)strlcpy(buf, s, sizeof(buf)); (void)strlcat(buf, p, sizeof(buf));
char *dir, *file, pname[MAXPATHNAMELEN];Because we know how many characters were copied the first time, using a copy instead of an append speeds execution a bit, although code like this largely defeats the purpose of strlcpy( ) and strlcat( ):...
if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname)) goto toolong; if (strlcat(pname, file, sizeof(pname)) >= sizeof(pname)) goto toolong;
char *dir, *file, pname[MAXPATHNAMELEN]; size_t n;...
n = strlcpy(pname, dir, sizeof(pname)); if (n >= sizeof(pname)) goto toolong; if (strlcpy(pname + n, file, sizeof(pname) - n) >= sizeof(pname) - n) goto toolong;