vsnprintf()可变参数的用法
来源:互联网 发布:淘宝装饰模板 编辑:程序博客网 时间:2024/04/28 02:54
1)Return Value
The number of charactersthat 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()可变参数的用法
- vsnprintf()可变参数的用法
- vsnprintf打印可变参数的log
- 有关va_list和vsnprintf输出函数的问题(可变参数)
- snprintf vsnprintf的用法
- va_list及vsnprintf的用法
- apue读书笔记【二】:处理可变参数(2) vsnprintf
- 关于可变参数的用法
- 可变个数参数的用法
- 可变参数宏的用法
- C语言中可变参数的用法
- C语言中可变参数的用法
- C语言中可变参数的用法
- C语言中可变参数的用法
- C语言中可变参数的用法
- C语言中可变参数的用法
- 可变参数va_start, va_arg, va_end的用法
- C语言中可变参数的用法
- 在由N个正整数的集合S中,找出最大元素C,满足C=A + B
- entities, symbol & character encoding
- 六、把文件存放在SDCard
- Windows中C:\WINDOWS\system32\drivers\etc\hosts文件的作用
- Web_PHP_PHP XML DOM编程:查询、添加、删除操作;
- vsnprintf()可变参数的用法
- 七、使用sax解析xml文件
- Josephus问题求解
- C++Primer第五版 练习11.7(解答)
- 八、使用pull解析器操作xml文件
- hdu 1010 Tempter of the Bone(DFS+剪枝)
- TCP/IP 和 OSI 模型
- 含有头结点的单链表,实现部分功能,希望大家能够给予指点
- [leetcode] 136 &137 Single Number Ⅰ Ⅱ