封装自己的打印函数:用于debug和输出log
需求:如何简便的输出调试信息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>/*包含va_list 和va_start _va_end的头文件*/
int debug = 1;/*定义全局变量作为打印开关*/
void debugprint(const char *fmt,...){
/*...的前面必须是char型的指针变量*/
if(debug){
va_list valist;/*c语言中可变参数的宏*/
char buff[512] = "abcd";
va_start(valist,fmt);
vsprintf(buff,fmt,valist);/*vsprintf(char *string,char *fmt,va_list parm)*/
va_end(valist);
}
return;
}
void debugwrite(const char* filename,const char *fmt,...){
va_list valist;/*c语言中可变参数的宏*/
FILE* fp; /*filename = xxx.txt*/
fp = fopen(filename,"w");
va_start(valist,fmt);
vfprintf(fp,fmt,valist);
va_end(valist);
fclose(fp);
return;
}
void debugappend(FILE* fp,const char *fmt,...){
va_list valist;/*c语言中可变参数的宏*/
if (fp == NULL){printf("Open File failed.\n");exit(0);}
va_start(valist,fmt);
vfprintf(fp,fmt,valist);
va_end(valist);
return;
}
int main(){
debugprint("%s::%s->%d\n",__FILE__,__FUNCTION__,__LINE__);
debugwrite("physicalparms.txt","%s::%s->%d\n",__FILE__,__FUNCTION__,__LINE__);
FILE* fp = fopen("testappend.txt","a");
debugappend(fp,"%s::%s->%d\n",__FILE__,__FUNCTION__,__LINE__);
debugappend(fp,"%s::%s->%d\n",__FILE__,__FUNCTION__,__LINE__);
debugappend(fp,"%s::%s->%d\n",__FILE__,__FUNCTION__,__LINE__);
fclose(fp);
return 0;
}
相关资料: