使用__VA_ARGS__和va_list 控制打印日志

来源:互联网 发布:三星淘宝旗舰店 编辑:程序博客网 时间:2024/05/24 07:07

输出日志的控制

// main.c #include<stdio.h>#define printf_debug(...)  printf( __VA_ARGS__)//#define printf_debug(format,...) printf(__FILE__"(%s:%d)"format"", __FUNCTION__, __LINE__, ##__VA_ARGS__)  int main(){    printf_debug("Hello MAIN %d, %s, %d\n", 1234, "aaa", 888);    return 0;}

输出 : Hello MAIN 1234, aaa, 888

使用 printf_debug(format,…) 可以输出更多的定位信息,如下

输出:main.c(main:8)Hello MAIN 1234, aaa, 888

但是如果需要输出更多信息,比如除了位置信息还需要显示时间信息,则使用宏定义就不方便了;
那么可以使用函数:

#include<stdio.h>#include <stdarg.h>#include<time.h>int printf_debug(const char * format, ...) {    va_list arg;    va_start(arg, format);    char string[256];    vsprintf(string,format,arg);    printf("[%s]%s", "debug", string);    va_end(arg);}int main(){    printf_debug("Hello MAIN %d, %s, %d\n", 1234, "aaa", 888);    return 0;}

输出 [debug]Hello MAIN 1234, aaa, 888

输出时间的函数

#include <stdio.h>#include <time.h>void printTime1();void printTime2();int main(){    printTime1();    printTime2();    return 0; }void printTime1(){    time_t timep;    time (&timep);    // TIME1 = Thu May 18 14:50:47 2017    printf("TIME1 = %s",ctime(&timep));  // ctime()函数自带换行}void printTime2(){    time_t t;     struct tm * a;     time(&t);     a=localtime(&t);     // TIME2 = 2017-05-18 14:50:47    printf("TIME2 = %4d-%02d-%02d %02d:%02d:%02d\n",        start_year+a->tm_year,1+a->tm_mon,a->tm_mday,        a->tm_hour,a->tm_min,a->tm_sec); }

本例程是在Ubuntu上实现的,关于在ANDROID平台下的JNI使用,移步:
http://blog.csdn.net/dreamintheworld/article/details/50318523