strlcpy和strlcat是BSD的C库函数,glibc维护者一直拒绝将其加入,所以需要安装额外的包。

函数原型:

size_t strlcpy(char *dstconst char *srcsize_t size);

size_t strlcat(char *dstconst char *srcsize_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
GitHub 加速计划 / li / linux-dash
10
2
下载
A beautiful web dashboard for Linux
最近提交(Master分支:1 个月前 )
186a802e added ecosystem file for PM2 5 年前
5def40a3 Add host customization support for the NodeJS version 5 年前
Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐