天天看点

snprintf和strncpy对比

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';

这个时候就正常了,当然也可以:

strncpy(dest1, src, sizeof(dest1)); // 前sizeof(dest1)个字节,src和dest1将完全相同

dest1[sizeof(dest1)-1] = '\0'; // 将第sizeof(dest1)-1个字节处置为结尾符'\0'

复制代码

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

从上也可以看出,不管是strncpy还是snprintf,它们都会尊重sizeof(),都不会向dest拷贝超过sizeof()大小的字节数。

    本文转自eyjian 51CTO博客,原文链接:http://blog.51cto.com/mooon/909473,如需转载请自行联系原作者

继续阅读