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.





  • 相关阅读:
    sqlserver 跟踪标志
    解决ORA-00338,ORA-00312
    oracle SQL性能分析
    高潜力人士和员工
    pymysqlreplication
    Python3操作Excel(写入)
    CentOS7.4 源码安装MySQL8.0
    MySql 时间操作实例
    python+eclipse+pydev开发环境搭建
    MySQL表结构同步工具 mysql-schema-sync
  • 原文地址:https://www.cnblogs.com/techsunny/p/3685707.html
Copyright © 2011-2022 走看看