vsnprintf()可变参数的用法

1)Return Value

The number of characters that would have been written if n had been sufficiently large, not counting the terminating null character. 

If an encoding error occurs, a negative number is returned

Notice that only when this returned value is non-negative and less than n, the string has been completely written.

2)vsnprintf()返回值:是 buf string 的总长度,但是不包括'\0'(谨记:非负且小于 buff 的尺寸)

先看manual:

vsnprintf:int vsnprintf(char *str, size_t size, const char*format, va_list ap);
write output to character sting str

returnvalue:the number of characters
printed (notincluding the trailing '\0' used to end output to strings). Thefunctions snprintf() and vsnprintf() do not write more than size bytes (including thetrailing '\0'). If the output was truncated due to this limitthen the return value is the number of characters (not including the trailing'\0') (与测试结果MS有点不相符合,见下,或者是另外一种理解:返回的仍然是字符数,这样的话就相符)which would have been written to the final string if enough spacehad been available. Thus, a return value of size or more means that the outputwas truncated. If an output error is encountered, a negative
value is returned.
if (return_value > -1) 
size = n+1;
else 
size *= 2;
测试函数:

#include <stdio.h>
#include <stdarg.h>
char buf[10];

int vspf(char *buf,int size,char *fmt,...)
{
        int cnt=0;
        va_list arg;
        va_start(arg,fmt);
        cnt = vsnprintf(buf,size,fmt,arg);
        va_end(arg);
        return cnt;
}

int main()
{
        char str[10]="abcdef";
        int a=10;
        int b=20;
        printf("b is %f\n",b);
        int cnt = vspf(buf,100,"%d %f%s",a,(float)b,str);
        printf("%s,cnt is%d\n",buf,cnt);
}
输出结果:

b is 0.000000
10 20.000000 abcdef,cnt is 19
结果分析:

vsnprintf()返回值:是buf string的总长度,但是不包括'\0'

如果改变     int cnt = vspf(buf,10,"%d %f%s",a,(float)b,str); (100->10)

b is 0.000000
10 20.000,cnt is 19
我们发现cnt的值没有变化,输出buf中包括了'\0',并且截断了字符串(也就是说只是输出了9个字符),此处并没有越界

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值