分类: C/C++
2010-07-30 15:31:43
zj@zj:~/C_parm/string/own_str/strcpy$ cat strcpy.c
/*
下面是strcpy库函数的实现,因为库函数讲究的就是精练、简洁。所以没有其他的异常处理代码。主要的异常处理还是交给了函数的使用者,在调用前请确认目的和源指针是否都存在(不能为Null),请确认目标指针空间是否大于源字符串的空间。
Copies the string src into the spot specified by dest; assumes enough room.
目标指针空间必须大于源字符串空间。
*/
#include<stdio.h>
#include<stdlib.h>
#define MAX_LEN 255
char* my_strcpy(char* dst, const char* src);
int main()
{
char a[MAX_LEN];
char* str = "Hello,world!";
printf("Copied:%s\n",my_strcpy(a,str));
exit(EXIT_SUCCESS);
}
char* my_strcpy(char* dst, const char* src)
{
if((dst==NULL)||(src==NULL))
perror("dst or src is null");
char* cp = dst;
while((*cp++=*src++)!='\0')
;
return (dst);
}
zj@zj:~/C_parm/string/own_str/strcpy$ ./strcpy
Copied:Hello,world!
zj@zj:~/C_parm/string/own_str/strncpy$ cat strncpy.c
/*Copies count characters from the source string to the destination.
* If count is less than the length of source,NO NULL CHARACTER is put
* onto the end of the copied string.If count is greater than the length
*of sources, dest is padded with null characters to length count.
*
* 把src所指由NULL结束的字符串的前n个字节复制到dest所指的数组中.如果src的
* 前n个字节不含NULL字符,则结果不会以NULL字符结束;
*如果src的长度小于n个字节,则以NULL填充dest直到复制完n个字节。
*src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串
*返回指向dest的指针.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_LEN 255
char* my_strncpy( char* dest, const char* source, int count );
int main()
{
char dst1[MAX_LEN];
char dst2[MAX_LEN];
char* src = "Hello,world!";
bzero(dst1,'\0');
bzero(dst2,'\0');
printf("After strncpy:%s\n",my_strncpy(dst1,src,15));
printf("After strncpy:%s\n",my_strncpy(dst2,src,10));
exit(EXIT_SUCCESS);
}
char* my_strncpy( char* dest, const char* source, int count )
{
if((dest==NULL)||(source==NULL))
perror("dest or source null");
char *p = dest;
while (count && (*dest++ = *source++)) count--;
while(count--)
*dest++ = '\0';
/*由于dest已经移动,返回的时候返回首地址就可以了*/
return(p);
/*while (count && (*p++ = *source++)) count--;
while(count--)
*p++ = '\0';
return(dest);*/
}
zj@zj:~/C_parm/string/own_str/strncpy$ ./strncpy
After strncpy:Hello,world!
After strncpy:Hello,worl ???????