vsnprintf()可变参数的用法

来源:互联网 发布:目标管理 知乎 编辑:程序博客网 时间:2024/04/28 14:12

先看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个字符),此处并没有越界