使用__VA_ARGS__和va_list 控制打印日志

// 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

转自:https://blog.csdn.net/dreamInTheWorld/article/details/72469454

猜你喜欢

转载自blog.csdn.net/zxx2096/article/details/81251972