StackOverFlow上的回答:
vprintf() (and friends) allow to use va_list as argument, which is useful when your function has a variable amount of arguments:
void log(FILE *file, const char* format, ... )
{
va_list args;
va_start (args, format);
fprintf(file, "%s: ", getTimestamp());
vfprintf (file, format, args);
va_end (args);
}
In your application you can call this function with a variable amount of arguments:
log(file, "i=%d\n", i); // 3 arguments
log(file, "x=%d, y=%d\n", x, y); // 4 arguments
简单说,函数使用不定长参数时,vprintf()函数将很有用,下面一个简单的例子,实现简易日志打印。
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
void FwriteLog(const char *FileName, int Line, const char *format, ...)
{
va_list ap;/* 定义保存函数参数的结构 */
FILE *fp;
int retval;
fp = NULL;
if((fp = fopen("abc.log", "a")) == NULL) {
return;
}
fprintf(fp, "源文件[%s]第[%d]行-", FileName, Line);
va_start(ap, format); /* ap指向传入的第一个可选参数,format是最后一个确定的参数 */
retval = vfprintf(fp, format, ap); /* 使用va_list类型参数 */
va_end(ap);
fprintf(fp, "%c", '\n');
fclose(fp);
fp = NULL;
return;
}
上面的函数这样使用:
FwriteLog(__FILE__, __LINE__, "error_code:%d, details:%s", 123, "some error.")