linux下使用strlcpy和strlcat

24 篇文章 0 订阅
1 篇文章 0 订阅

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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值