zoukankan      html  css  js  c++  java
  • snprintf和strncpy对比

    有关snprintf返回值更多信息,请参考:http://bbs.hadoopor.com/thread-1185-1-1.html

    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()大小的字节数。
  • 相关阅读:
    mac重启nginx时报nginx.pid不存在的解决办法
    js 正则表达式
    js 闭包
    js yarn
    js npm
    vue3 vite
    node 错误处理
    node fs
    linux包管理工具使用和区别(转)
    MySQL数据库学习----理论基础
  • 原文地址:https://www.cnblogs.com/aquester/p/9891874.html
Copyright © 2011-2022 走看看