这是可以自定义的printf? [英] Is this possible to customize printf?
问题描述
我有一些结构,我需要经常打印。现在,我使用的是传统的印刷包装解决此结构:
I have some struct that I need to print frequently. For now, I am using a classical print wrapper around this struct :
void printf_mystruct(struct* my_struct)
{
if (my_struct==NULL) return;
printf("[value1:%d value2:%d]", struct->value1, struct->value2);
}
此功能是方便,但也实在有限。我不能prepen或追加一些文本而不进行新的包装。我知道我可以使用在va_arg 家庭能够prePEND或AP preND一些文字,但我觉得我会被重新实现轮。
This function is handy, but is also really limited. I cannot prepen or append some text without making a new wrapper. I know that I can use va_arg family to be able to prepend or apprend some text, but I feel like I would be re-implementing the wheel.
我想知道是否有可能写一个定制功能的printf。我希望能够写这样的事:
I am wondering if it's possible to write a customizing function to printf. I would like to be able to write something like this :
register2printf("%mys", &printf_mystruct);
...
if (incorrect)
printf("[%l] Struct is incorrect : %mys\n", log_level, my_struct);
这可能吗?我怎样才能做到这一点?
Is this possible ? How can I do this ?
注:我在Ubuntu Linux操作系统和10.04我用gcc
NB: I am under Ubuntu Linux 10.04 and I use gcc.
推荐答案
很抱歉,但一些答案不正确,在Linux上用glibc
在Linux上使用GNU的glibc,可以定制的printf :您会打电话 register_printf_function
来如在你的的printf
格式字符串定义%Y
的含义。
On Linux with a GNU Glibc, you can customize printf: you would call
register_printf_function
to e.g. define the meaning of %Y
in your printf
format strings.
但是,这种行为是具体的Glibc,甚至可能会过时...我不知道我会推荐这种方法!
However, this behavior is Glibc specific, and might even become obsolete... I'm not sure I would recommend this approach!
如果用C编码++中,C ++流库有哪些可以扩展操纵,你也可以超载为你的类型的运营商的LT;<
等
If coding in C++, the C++ stream library has manipulators which you could extend, and you can also overload for your types the operator <<
etc.
这篇关于这是可以自定义的printf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!