根据用户偏好进行过滤的包装 printf 函数 [英] wrapper printf function that filters according to user preferences
问题描述
我的程序写入日志和标准输出.然而,每条消息都有一个特定的优先级,用户在首选项中指定哪些优先级属于哪个流(日志或标准输出).
My program writes to a log and to stdout. Every message, however, has a certain priority and the user specifies in Preferences which priorities go to which stream (log or stdout).
unsigned short PRIO_HIGH = 0x0001;
unsigned short PRIO_NORMAL = 0x0002;
unsigned short PRIO_LOW = 0x0004;
偏好由一些标志处理:
unsigned short PRIO_LOG = (PRIO_HIGH | PRIO_NORMAL);
unsigned short PRIO_STD = (PRIO_HIGH);
write_log
函数应该使用与 printf 函数相同的参数,但增加了 unsigned short priority
参数.
The write_log
function should work with the same parameters as the printf function, with the added parameter of unsigned short priority
.
write_log((PRIO_NORMAL|PRIO_LOW), "HELLO %s, take %d", "World", 1);
(即使 PRIO_NORMAL|PRIO_LOW
毫无意义...)
(Even if PRIO_NORMAL|PRIO_LOW
makes little sense...)
检查标志很容易:if(priority & PRIO_LOG)
(如果在两个参数中都设置了任何标志,则返回 >1)
Checking the flags is easy: if(priority & PRIO_LOG)
(Returns >1 if any flag is set in both arguments)
然而,我不知道如何将字符串文字 和 格式参数传递给 printf 函数.任何人都可以帮助或给我一个指针(可能是达到相同效果的替代方法)?将不胜感激.
I cannot however find out how I would go about passing the string literal and the format arguments to the printf function. Can anyone help or give me a pointer (possible to an alternative method that achieves the same effect)? It would be much appreciated.
推荐答案
您想使用可变参数 "varargs" C 的能力.
You want to call vprintf() instead of printf() using the variable arguments "varargs" capabilities of C.
#include <stdarg.h>
int write_log(int priority, const char *format, ...)
{
va_list args;
va_start(args, format);
if(priority & PRIO_LOG)
vprintf(format, args);
va_end(args);
}
有关详细信息,请参阅this.
For more information, see something along the lines of this.
这篇关于根据用户偏好进行过滤的包装 printf 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!