Linux可变参数打印日志(二)

#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
#include<string.h>

#define my_printf(fmt,...) debug_printf(__FILE__,__FUNCTION__,__LINE__,fmt,##__VA_ARGS__)
const char *logPath = "./log.txt";

void debug_printf(const char *file,const char *fun,const int line,const char *fmt, ...)
{
    va_list arg_ptr;
    va_list arg_tmp;
    va_start(arg_ptr,fmt);
    va_copy(arg_tmp,arg_ptr);

    printf("[%s %s %d] ",file,fun,line);
    vprintf(fmt,arg_ptr);

    FILE *pf = NULL;
    pf = fopen(logPath,"a");
    if(NULL != pf)
    {
        fprintf(pf,"[%s %s %d] ",file,fun,line);
        vfprintf(pf,fmt,arg_tmp);
        fclose(pf);
        pf = NULL;
    }    
    va_end(arg_ptr);    
}

int main()
{    
    int i = 1;
    my_printf("this is my %d test",i);
    return 0;
}

运行结果:

 

posted @ 2019-07-10 17:21  王清河  阅读(370)  评论(0编辑  收藏  举报