1. 程式人生 > >linux系統庫函式之strcpy、strncpy

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位元組大小資料,二是,如果拷貝的資料沒有字串結束符,它還可以自己結束資料拷貝。