linux系统库函数之strcpy、strncpy

 91 #ifndef __HAVE_ARCH_STRCPY
 92 /**
 93  * strcpy - Copy a %NUL terminated string
 94  * @dest: Where to copy the string to
 95  * @src: Where to copy the string from
 96  */
 97 #undef strcpy
 98 char *strcpy(char *dest, const char *src)
 99 {
100         char *tmp = dest;
101 
102         while ((*dest++ = *src++) != '\0')
103                 /* nothing */;
104         return tmp;
105 }
106 EXPORT_SYMBOL(strcpy);

107 #endif

strcpy函数为字符串拷贝函数,它只能拷贝字符串,遇到字符串的结束符'/0'拷贝结束。要是没有这个结束符,后果可想而知。

109 #ifndef __HAVE_ARCH_STRNCPY
110 /**
111  * strncpy - Copy a length-limited, %NUL-terminated string
112  * @dest: Where to copy the string to
113  * @src: Where to copy the string from
114  * @count: The maximum number of bytes to copy
115  *
116  * The result is not %NUL-terminated if the source exceeds
117  * @count bytes.
118  *
119  * In the case where the length of @src is less than  that  of
120  * count, the remainder of @dest will be padded with %NUL.
121  *
122  */
123 char *strncpy(char *dest, const char *src, size_t count)
124 {
125         char *tmp = dest;
126 
127         while (count) {
128                 if ((*tmp = *src) != 0)
129                         src++;
130                 tmp++;
131                 count--;
132         }
133         return dest;
134 }
135 EXPORT_SYMBOL(strncpy);
136 #endif

strncpy也是字符串拷贝函数,遇到字符串结束符就停止拷贝,但它和strcpy不同的是,如果没有遇到字符串结束符,它只拷贝count字节大小数据。有两种用途,一是,我只需要count字节大小数据,二是,如果拷贝的数据没有字符串结束符,它还可以自己结束数据拷贝。

posted @ 2012-03-20 14:04  移动应用开发  阅读(497)  评论(0编辑  收藏  举报