zoukankan      html  css  js  c++  java
  • 被strncpy搞糊涂的snprintf

    摘自man文档: The strncpy() function is similar, except that at most n bytes of src are copied.  Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

    为了确保dest以''结尾, 一般要写成:
    dest[sizeof(dest) - 1] = '';
    strncpy(dest, src, sizeof(dest) - 1);

    snprintf()会确保以''结尾, 不需要设置dest末尾的'', 一般写成:
    snprintf(dest, sizeof(dest), ...)
    strlen(dest)的最大长度为sizeof(dest) - 1.

    摘自man文档: The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('')).  If the output was truncated due to this limit  then  the  return value  is  the  number  of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available.  Thus, a return value of size or more means that the output was truncated.  (See also below under NOTES.)

    例如:
    char str[64] = { 0 };
    snprintf(str, 3, "abc");
    printf("%s ", str);
    结果: ab

    一直以来, 将snprintf像strncpy一样用了, 才发现不用那么费事...

    还有strncat(), 不需要设置dest末尾的'', 但需要n + 1的空间.
    摘自man文档: If src contains n or more characters, strncat() writes n+1 characters to dest (n from src plus the terminating null byte).  Therefore, the size of dest must be at least strlen(dest)+n+1.





  • 相关阅读:
    win10新特性,ubuntu子系统(安装及配置)
    excel计算后列填充
    word中利用宏替换标点标点全角与半角
    CFD-post的奇技淫巧
    mfix模拟流化床燃烧帮助收敛的方法
    cygwin下配置alias
    endnote 使用方法
    win8系统换win7系统
    python中的函数以及递归
    01python算法--算法和数据结构是什么鬼?
  • 原文地址:https://www.cnblogs.com/techsunny/p/3685707.html
Copyright © 2011-2022 走看看