strcpy和strncpy摘于linux 内核源码的/lib/string.c
char *self_strcpy(char *dest, const char *src)
{
char *tmp = dest;
while ((\*dest++ = \*src++) != '\\0')
/\* nothing \*/;
return tmp;
}
char *self_strncpy(char *dest, const char *src, size_t count)
{
char *tmp = dest;
while (count) {
if ((\*tmp = \*src) != 0)
src++;
tmp++;
count--;
}
return dest;
}
针对处理self_strncpy_s函数接口
个人定义self_strncpy_s接口,目的是解决,防止溢出,在不够buffer时可以处理最大值的字符串数据。
例如:
|0000000000|
|xxxxxxxxxxx| 复制到
|00000000| 得到结果是
|xxxxxxxxx|
源码实现:
char *self_strncpy_s(char *dest, size_t buffer, const char *src, size_t size)
{
if (size > buffer)
size = buffer;
char \*tmp = dest;
while (size) {
if ((\*tmp = \*src) != 0)
src++;
tmp++;
size--;
}
dest\[buffer\] = '\\0';/\*avoid ending symbol character\*/
return dest;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章