C99中:
#define print_LOG(format, ...) fprintf(stdout, format, __VA_ARGS__)
其中,…表示参数可变,__VA_ARGS__在预处理中为实际的参数集所替换
GCC中同时支持如下的形式
#define print_LOG(format, args...) fprintf(stdout, format, args)
改进一
#define print_LOG(format, ...) fprintf(stdout, format, ##__VA_ARGS__)
#define print_LOG(format, args...) fprintf(stdout, format, ##args)
"##"的作用是对token进行连接
改进二
#ifdef DEBUG
#define print_LOG(format, ...) fprintf(stdout, ">> "format"\n", ##__VA_ARGS__)
#else
#define print_LOG(format, ...)
#endif
实例
#include <stdio.h>
#include <string.h>
int write_file(char *filename, char *buff, int len)
{
//open
FILE *fp;
int ret;
fp = fopen(filename, "w");
if(fp == NULL)
{
printf("鎵撳紑鏂?s浠跺け璐n",filename);
return 0;
}
//write
ret = fwrite(buff, 1, len, fp);
if(ret != len)
{
printf("鍐欏叆%s鏂囦欢澶辫触",filename);
}
//close
fclose(fp);
}
int read_file(char *filename, char *buff, int len)
{
//鎵撳紑鏂囦欢
FILE *fp;
int ret;
fp = fopen(filename, "r");
if(fp == NULL)
{
printf("鎵撳紑鏂?s浠跺け璐n",filename);
return 0;
}
ret = fread(buff, 1, len, fp);
//鍏抽棴鏂囦欢
fclose(fp);
return ret;
}
char file_buff[2048] = {0};
#define print_LOG(format, ...) {\
memset(file_buff, 0, 2048);\
sprintf(file_buff, format, ##__VA_ARGS__);\
write_file("uart_log.txt", file_buff, strlen(file_buff));}
int main()
{
print_LOG("hello guoguo%d\n",12345);
return 0;
}