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字节大小数据,二是,如果拷贝的数据没有字符串结束符,它还可以自己结束数据拷贝。

原文链接: https://www.cnblogs.com/phonegap/archive/2012/03/20/2536111.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    linux系统库函数之strcpy、strncpy

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/44645

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午9:17
下一篇 2023年2月8日 下午9:17

相关推荐