strlcpy和strlcat是BSD的C库函数,glibc维护者一直拒绝将其加入,所以需要安装额外的包。
函数原型:
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 NUL-terminated string src to the end of dst. It will append at most size -
strlen(dst) - 1 bytes, NUL-terminating the result.
上面的size-1才是重点,strlcpy在拷贝时,如果size刚好是char *dst的大小,会少拷贝一个字符,最后一个字符填结束符'\0'。而strncpy会拷贝size个字符,没有结束符'\0',strlcat类似。
#include <string.h>
#include <stdio.h>
#include <bsd/string.h>
int main(void)
{
char *pstr1 = new char[10];
memset(pstr1,'h',10);
char *pstr2 = new char[20];
memset(pstr2,'H',20);
strncpy(pstr1,pstr2,10);
printf("strncpy:%s\n",pstr1);
memset(pstr1,'a',10);
strlcpy(pstr1,pstr2,10);
printf("strlcpy:%s\n",pstr1);
delete[] pstr1;
delete[] pstr2;
return 0;
}
输出:
strncpy:HHHHHHHHHH
strlcpy:HHHHHHHHH
可以看到strlcpy只拷贝了9个字符,而strncpy拷贝了10个。
注意:需要安装bsd库,编译时加上-lbsd.
Debian系列:
apt-get install libbsd-dev
红帽系类要安装的是
yum install libbsd-devel