fprintf和vfprintf

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.")

转载于:https://my.oschina.net/llehs/blog/181975

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值