初识回显控制
昨天在群里有朋友提到回显控制,以前从没听说过,所以一时兴起,今天就乘着SVN下载代码期间学习一下,话不多说直接贴代码:
#include <stdio.h> #include <stdarg.h> //回显类型 typedef enum { NONE_ECHO = 0, ERROR_ECHO = (1 << 0), WARNING_ECHO = (1 << 1), DEBUGGING_ECHO = (1 << 2), }echo_type_e; //回显授权控制 typedef enum { DISABLE_ALL = 0, ENABLE_ERROR = (1 << 0), ENABLE_WARNING = (1 << 1), ENABLE_DEBUGGING = (1 << 2), DISABLE_ERROR = ~(1 << 0), DISABLE_WARNING = ~(1 << 1), DISABLE_DEBUGGING = ~(1 << 2), }EnableEcho_e; typedef struct { int ID; char name[100]; EnableEcho_e Debug; }MyStruct_t; //回显打印函数 void echoCtrl(EnableEcho_e myType, EnableEcho_e type, const char* file, const int line, const char *msg, ...) { char temp[1024]; va_list args; va_start(args, msg); vsprintf(temp, msg, args); va_end(args); switch (type) { case NONE_ECHO: break; case ERROR_ECHO: if (ERROR_ECHO & myType) { printf("\033[0;41m [ERROR] [%s, %d]", file, line); printf(temp, (void *)0); printf("\033[0m\n"); } break; case WARNING_ECHO: if (WARNING_ECHO & myType) { printf("\033[0;42m [WARNNING] [%s, %d]", file, line); printf(temp, (void *)0); printf("\033[0m\n"); } break; case DEBUGGING_ECHO: if (DEBUGGING_ECHO & myType) { printf("\033[0;44m [DEBUG] [%s, %d]", file, line); printf(temp, (void *)0); printf("\033[0m\n"); } break; default: break; } } //可变参数函数的两个宏定义写法 #define OUTPUT_ERROR(type, msg, ...) echoCtrl(type, ERROR_ECHO, __FILE__, __LINE__, msg, __VA_ARGS__) //第一种 #define OUTPUT_WARNNING(type, msg...) echoCtrl(type, WARNING_ECHO, __FILE__, __LINE__, ##msg) //第二种 #define OUTPUT_DEBUG(type, msg, ...) echoCtrl(type, DEBUGGING_ECHO, __FILE__, __LINE__, msg, __VA_ARGS__) int main() { //打开错误和警告回显 MyStruct_t my_obj = {10010, "chen", ENABLE_ERROR | ENABLE_WARNING}; OUTPUT_ERROR(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); OUTPUT_WARNNING(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); OUTPUT_DEBUG(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); //打开错误和调试回显,关闭警告回显 my_obj.Debug &= DISABLE_WARNING; my_obj.Debug |= ENABLE_DEBUGGING; printf("------------------------------------\n"); OUTPUT_ERROR(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); OUTPUT_WARNNING(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); OUTPUT_DEBUG(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); //关闭所有回显 my_obj.Debug &= DISABLE_ALL; printf("------------------------------------\n"); OUTPUT_ERROR(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); OUTPUT_WARNNING(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); OUTPUT_DEBUG(my_obj.Debug, "my_id:%d, my_name:%s", my_obj.ID, my_obj.name); return 0; }