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()大小的字节数。
  • 相关阅读:
    PowerDesigner概念设计模型(CDM)中的3种实体关系
    基于Prototype 1.6.2 框架下的数据分页
    中国地区,北京54坐标系条带号的选
    C#中MessageBox的使用
    C#注册表的读,写,删除,查找 (转)
    C# Tostring() 格式大全 [转]
    Layer features in this layer set, ArcEngine图层标注源码 (转)
    判断点是否在多边形之内的方法
    C#导入Excel到Dataset和导出Excel到DataTable
    Server.MapPath方法的应用方法
  • 原文地址:https://www.cnblogs.com/aquester/p/9891874.html
Copyright © 2011-2022 走看看