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.





  • 相关阅读:
    asp.net 学习连接
    学习笔记一
    windows 2008 r2 AD密码策略
    Windows Server 2008 R2之活动目录回收站
    用java 调用 .net 自定义的 Soap WEB Service
    昆明赶街时间
    Windows Server 2008 R2 AD的备份和恢复
    AD 自定义属性
    AD、IIS、asp.net
    wsgen与wsimport命令说明
  • 原文地址:https://www.cnblogs.com/techsunny/p/3685707.html
Copyright © 2011-2022 走看看