重写string.h中的字符串操作函数--strncpy

本文重写了string.h中的strncpy函数,并参照linux/lib/string.c中的函数原型及MSDN定义。通过实验验证了当复制字符数量超过源字符串长度时,目标字符串末尾会正确填充空字符。

 

这是我第一次写博客,文中可能有些错误或者需要继续改进的地方,希望大家能够帮我发现不足啊,呵呵。

本文重写了string.h中的一些函数,参考了linux/lib/string.c中的函数原型和MSDN中函数的定义。虽然是重写,但是改变的并不多,因为linux中的定义基本是最优的,我曾经对有些函数能否实现其功能产生过怀疑,但是结果可能并非我所猜测,所以每个函数我都会在VC下试验一下,检验其执行结果。

1.strncpy
prototype:
char *strncpy(char *strDest, const char *strSource, size_t count);
description:
The function strncpy is used to copy the initial count character of strSource to strDest and return strDest; If the count is less than or equal to the length of strSource, a null character will not append automatically to strDest. But if the count is greater than the length of strSource, the strDest will be padded with the null character up to the count.
 
defined in Linux:
 char * strncpy(char * dest,const char *src,size_t count)
{
char *tmp = dest;
 while (count-- && (*dest++ = *src++) != '/0')
 /* nothing */;

return tmp;
}
 
Modified:
我曾经根据MSDN里的定义对逐个函数进行了大部分的修改,因为我觉得当count 大于src的长度时,上述定义可能并没有实现在dest的末尾填充count - strlen(src)个'/0'。但是调用它时发现能够实现。
   
char * strncpy(char * dest,const char *src,size_t count)
{
assert((NULL != dest) && (NULL != src));
char *tmp = dest;
/* if the length of src is less than count, the null character will paded in the end of dest up to 
 *count automatically
*/
 while (count-- && (*dest++ = *src++) != '/0')
 /* nothing */;

return tmp;
}

Note:本函数存在一定的缺陷,如果strDest的长度小于要存入的字符的个数,则会发生越界,所以建议这样使用:

strncpy(strDest, strSource, strlen(strDest));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值