Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8049102
  • 博文数量: 594
  • 博客积分: 13065
  • 博客等级: 上将
  • 技术积分: 10324
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-26 16:44
个人简介

推荐: blog.csdn.net/aquester https://github.com/eyjian https://www.cnblogs.com/aquester http://blog.chinaunix.net/uid/20682147.html

文章分类

全部博文(594)

分类: C/C++

2010-08-19 10:03:09

有关snprintf返回值更多信息,请参考:

snprintf MAN手册:
The functions snprintf() and vsnprintf()  do  not  write  more  than  size  bytes  (including  the trailing '\0')
这句话表示snprintf总是会将'\0'写入。

strncpy MAN手册:
The  strncpy() function is similar, except that not more than n bytes of src are copied. Thus, if there is no null  byte among the first n bytes of src, the result will not be null-terminated.
这句话表明如果源字符串比指定的目标长度大,则不会写入'\0',也就是strncpy总是严格尊守指定大小,绝不越雷池半步,也绝不做份外的工作,可以理解成死板。

从上可以看出,snprintf和strncpy用法稍有不同,分别如下:
char dst[X];
char src[Z];
snprintf(dst, sizeof(dst), "%s", src);

strncpy(dst, src, sizeof(dst)-1);
dst[sizeof(dst)-1] = '\0';

测试代码:
int main()
{
    char dest1[3];
    char dest2[3];
    char src[] = "0123456789";

    printf("src[2]=%d,%c\n", src[2], src[2]);

    strncpy(dest1, src, sizeof(dest1)-1);
    printf("dest1[2]=%d,%c\n", dest1[2],dest1[2]);  // dest1[2]是一个未初始化的随机

    snprintf(dest2, sizeof(dest2), "%s", src);
    printf("dest2[2]=%d,%c\n", dest2[2],dest2[2]); // dest2[2]总是一个C字符串结尾符'\0'

    return 0;
}

也就是strncpy总是拷贝指定大小的字节数,绝不会多做,所以不会自动加结尾符'\0',除非指定大小的字节数范围内的src已经包含了结尾符'\0'。
但snprintf总是只拷贝指定大小减1后的字节数,然后再自动加上结尾符'\0'。因此对于上述strncpy的用法,还应当加上:
dest1[sizeof(dest1)-1] = '\0';
这个时候就正常了,当然也可以:
  1. strncpy(dest1, src, sizeof(dest1)); // 前sizeof(dest1)个字节,src和dest1将完全相同
  2. dest1[sizeof(dest1)-1] = '\0'; // 将第sizeof(dest1)-1个字节处置为结尾符'\0'
复制代码

所以对于strncpy是否需要sizeof()-1,也并非必要的,完全可以只sizeof(),但一定得再加上结尾符'\0'。

从上也可以看出,不管是strncpy还是snprintf,它们都会尊重sizeof(),不会向dest拷贝超过sizeof()大小的字节数。
阅读(1871) | 评论(0) | 转发(2) |
0

上一篇:Hadoop技术论坛

下一篇:有关snprintf返回值

给主人留下些什么吧!~~