Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2115326
  • 博文数量: 374
  • 博客积分: 7276
  • 博客等级: 少将
  • 技术积分: 5668
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-06 16:35
文章分类

全部博文(374)

文章存档

2013年(23)

2012年(153)

2011年(198)

分类: LINUX

2011-10-20 15:28:51

strlcpy函数返回的是源字符串的长度  strlcat函数返回的是源字符串+目的字符串的长度   程序可通过返回的值
和目的字符串的SIZE比较  就可以知道在拷贝、粘帖过程中是否发生了截断 
strlcpy函数源码如下

#include
20#include
21 
22/**
23 * Copy src to string dst of size siz.  At most siz-1 characters
24 * will be copied.  Always NUL terminates (unless siz == 0).
25 * Returns strlen(src); if retval >= siz, truncation occurred.
26 */
27size_t
28strlcpy(char *dst, const char *src, size_t siz)
29{
30        char *d = dst;
31        const char *s = src;
32        size_t n = siz;
33 
34        /** Copy as many bytes as will fit */
35        if (n != 0) {
36                while (--n != 0) {
37                        if ((*d++ = *s++) == '\0')
38                                break;
39                }
40        }
41 
42        /** Not enough room in dst, add NUL and traverse
            rest of src */
43        if (n == 0) {
44                if (siz != 0)
45                        *d = '\0'; /** NUL-terminate dst */
46                while (*s++)
47                        ;
48        }
49 
50        return(s - src - 1);        /** count does not include NUL */
51}

用法示例:

len = strlcpy(path, homedir,sizeof(path);
if (len >= sizeof(path))
return (ENAMETOOLONG);
len = strlcat(path, "/",sizeof(path);
if (len >= sizeof(path))
return (ENAMETOOLONG);
len = strlcat(path, ".foorc",sizeof(path));
if (len >= sizeof(path))
return (ENAMETOOLONG);



阅读(1317) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~