vsnprintf和snprintf是C语言printf家族函数的成员,相关函数列表如下:
#include <stdio.h>
int printf(const char *format, ...); //输出到标准输出
int fprintf(FILE *stream, const char *format, ...); //输出到文件
int sprintf(char *str, const char *format, ...); //输出到字符串str中
int snprintf(char *str, size_t size, const char *format, ...); //按size大小输出到字符串str中
以下函数功能与上面的一一对应相同,只是在函数调用时,把上面的...对应的一个个变量用va_list调用所替代。在函数调用前ap要通过va_start()宏来动态获取。
#include <stdarg.h>
int vprintf(const char *format, va_list ap);
int vfprintf(FILE *stream, const char *format, va_list ap);
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
可变参数列表va_list宏说明:
void FAULT_ln(char* format, ...){char i=0;
va_list vArgList;
va_start (vArgList, format);
i=vsnprintf(flash_data.USER_FAULT, 200, format, vArgList);
va_end(vArgList);
printf("%s\r\n",flash_data.USER_FAULT);
}
void INFO_ln(char* format, ...)
{char i=0;
va_list vArgList;
va_start (vArgList, format);
i=vsnprintf(flash_data.MORE_INFO, 200, format, vArgList);
va_end(vArgList);
printf("%s\r\n",flash_data.MORE_INFO);
}
用法实例
1 #include <stdio.h> 2 #include <stdarg.h> 3 int mon_log(char* format, ...) 4 { 5 char str_tmp[50]; 6 int i=0; 7 va_list vArgList; //定义一个va_list型的变量,这个变量是指向参数的指针. 8 va_start (vArgList, format); //用va_start宏初始化变量,这个宏的第二个参数是第一个可变参数的前一个参数,是一个固定的参数 9 i=_vsnprintf(str_tmp, 50, format, vArgList); //注意,不要漏掉前面的_ 10 va_end(vArgList); //用va_end宏结束可变参数的获取 11 return i; //返回参数的字符个数中间有逗号间隔 12 } 13 //调用上面的函数 14 void main() 15 { 16 int i=mon_log("%s,%d,%d,%d","asd",2,3,4); 17 printf("%d\n",i); 18 }
输出 9。
asd,2,3,4
返回值用法
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <stdarg.h> 4 char *make_message(const char *fmt, ...) 5 { 6 /* 初始时假设我们只需要不超过100字节大小的空间 */ 7 int n, size = 100; 8 char *p; 9 va_list ap; 10 if ( (p = (char *) malloc(size*sizeof(char))) == NULL) 11 return NULL; 12 while (1) 13 { 14 /* 尝试在申请的空间中进行打印操作 */ 15 va_start(ap, fmt); 16 n = vsnprintf (p, size, fmt, ap); 17 va_end(ap); 18 /* 如果vsnprintf调用成功,返回该字符串 */ 19 if (n > -1 && n < size) 20 return p; 21 /* vsnprintf调用失败(n<0),或者p的空间不足够容纳size大小的字符串(n>=size),尝试申请更大的空间*/ 22 size *= 2; /* 两倍原来大小的空间 */ 23 if ((p = (char *)realloc(p, size*sizeof(char))) == NULL) 24 return NULL; 25 } 26 } 27 int main() 28 { 29 /* 调用上面的函数 */ 30 char* str = make_message("%d,%d,%d,%d",5,6,7,8); 31 printf("%s\n",str); 32 free(str); 33 /* we allocate the memory in the make_message function, so we should release it by caller(main function). */ 34 return 0; 35 }