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

 

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

本文重写了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));

 

你可能感兴趣的:(重写string.h中的字符串操作函数--strncpy)