重写string.h中的字符串操作函数--strncpy
来源:互联网 发布:庞绍堂 知乎 编辑:程序博客网 时间:2024/06/05 17:06
这是我第一次写博客,文中可能有些错误或者需要继续改进的地方,希望大家能够帮我发现不足啊,呵呵。
本文重写了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;
}
{
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;
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;
}
while (count-- && (*dest++ = *src++) != '/0')
/* nothing */;
return tmp;
}
Note:本函数存在一定的缺陷,如果strDest的长度小于要存入的字符的个数,则会发生越界,所以建议这样使用:
strncpy(strDest, strSource, strlen(strDest));
- 重写string.h中的字符串操作函数--strncpy
- 重写string.h中的字符串操作函数--strcpy
- 重写string.h中的字符串操作函数--strcat
- 重写string.h中的字符串操作函数--strncat
- 重写string.h中的字符串操作函数--strcmp
- 重写string.h中的字符串操作函数--strncmp
- 重写string.h中的字符串操作函数--strchr
- 重写string.h中的字符串操作函数--memmove、memcpy
- 重写string.h中的字符串操作函数--strspn和strcspn
- 重写string.h中的字符串操作函数--memmove、memcpy
- 重写string.h中的字符串操作函数--strlen,strlen 与sizeof的区别
- string.h中常用字符串操作函数
- 重写strncpy函数
- strcpy,strncpy函数实现——string.h库函数
- string.h中的函数
- string.h中的函数
- string.h中的函数
- string.h中的函数
- 老友记台词学习笔记 SE01EP03(三)
- LDAP - 数据存储的一种思考方式
- 做人做事要有上进心9
- Ajax XMLHttpRequest 用法
- java网络编程(4)
- 重写string.h中的字符串操作函数--strncpy
- SnipeSword(狙剑) v5.0.1.9 (1206版)
- 关于sharepoint菜单的修改
- 做人做事要有上进心10
- ASP.NET 2.0 本地化技术之研究(1)
- web架构设计经验分享
- windows下的tail
- X-Ways.WinHex.v14.6.Incl.Keymaker-ZWT
- ASP.NET 2.0 本地化技术之研究(二)