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个字符),此处并没有越界
本文详细解析了vsnprintf函数的工作原理及返回值含义。介绍了如何通过该函数将格式化的字符串写入到指定大小的缓冲区中,并分析了在不同情况下函数的返回值及其意义。
218

被折叠的 条评论
为什么被折叠?



