vsprintf是你在找什么。它可以让你编写自己的类似sprintf的函数,它接受可变数量的参数,然后让你在进行调用之前做你需要的。
这里是我用它来实现自己的printf到USB端点在嵌入式设备中的例子:
#include <stdarg.h>
void uprintf(char *fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf(str_buffer, fmt, args);
usb_write(str_buffer);
va_end(args);
}
在你的情况,你可以“拦截”的格式调用vsprintf
,字符串并将自己的语法扩展为适当的格式说明符语法,然后将新的格式说明符和变量arg列表传递到vsprintf
。
void your_printf(char *fmt, ...) {
char new_fmt_string[1024]; /* make sure you allocate enough space */
va_list args;
/* here, do your transformation on the fmt string */
va_start(args, new_fmt_string);
vsprintf(str_buffer, new_fmt_string, args);
/* now take your fully formatted string and do something with it */
/* then clean up */
va_end(args);
}
[下载开源实现](http://www.gnu.org/software/libc/download.html)'printf'并对其进行破解。 –
@JonathonReinhart然后被迫释放你为这个项目编写的所有其他代码,因为它是一个“派生工作”。绝对没有人可以反对!这就是说,对于OP来说,还有更多的宽松许可的stdio/libc在那里;如果没有别的,只需从其中一个BSD变体中抽取一个。 – tbert
伙计们,如果你真的认为hacking printf是正确的方法,你真的需要检查vsprintf。 –