snprintf()函数返回值

函数原型:
int snprintf(char *str, size_t size, const char *format, ...);
 
size 的作用就是限制往str写入不超过size个字节(包括了结尾的'\0')。
因为sprintf()函数如果成功的话,返回成功写入的字节数(字符数),我就一直以为snprintf()函数也是如此,也就是snprintf()函数不会返回大于size的整数。
 
看下面一段手册内容:
 
The functions snprintf() and vsnprintf() do not  write  more than size bytes (including the trailing ’\0’). If the output was truncated due to this limit then the return value is the number of  characters (not including the trailing ’\0’) 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.
 

如果输出因为size的限制而被截断,返回值将是“如果有足够空间存储,所 能输出的字符数(不包括字符串结尾的'\0')”,这个值和size相等或者比size大!也就是说,如果可以写入的字符串是 "0123456789ABCDEF"共16位,但是size限制了是10,这样 snprintf() 的返回值将会是 16 而不是 10!

snprintf函数会自动的在结尾加上'\0', 不管size限制超过没有, 如果超过, 怎加上 '\0' 字符一共是size个。

 
上面的内容还说,如果返回值等于或者大于size,则表明输出字符串被截断了(truncated)。

转载于:https://my.oschina.net/jhdoctor/blog/95865

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值