在开发中,经常会用到打印,而这些打印在程序运行阶段不需要,仅在调试或开启现象的时候需要,我们用printf来打印往往不能对其进行灵活的控制,这个时候,我们就可以自己封装一个与printf功能相同的打印函数,加一些调试开关,就可以。
用到的接口:
#include <stdarg.h>
int vprintf(const char *format, va_list ap);
#include <stdio.h>
int vsnprintf(char *str, size_t size, const char *format, va_list ap);
vprintf() write output to std‐out, the standard output stream; 这是一个标准输出流函数。
vsnprintf() write at most size bytes (including the terminating null byte ('\0')) to str. 这个函数将包括空字符在内的字节写进字符串。
另外两个遍历参数的函数接口:
#include <stdarg.h>
void va_start(va_list ap, last);
void va_end(va_list ap);
解释摘自linux man手册
va_start()
The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.
The argument last is the name of the last argument before the variable argument list, that is, the last argument of which the calling function knows the
type.
Because the address of this argument may be used in the va_start() macro, it should not be declared as a register variable, or as a function or an array
type.
va_end()
Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function. After the call va_end(ap) the variable ap
is undefined. Multiple traversals of the list, each bracketed by va_start() and va_end() are possible. va_end() may be a macro or a function.
注意,这两个函数成对使用。
封装可变参数打印函数:
#include <stdarg.h>
#define DEBUG_SIZE 1024
void Debugoutput(const char * pcFmt, ...)/* valuable */
{
char szFormt[DEBUG_SIZE];
va_list valist;
va_start(valist, pcFmt);
vsnprintf(szFormt, sizeof(szFormt), pcFmt, valist);
vprintf(szFormt, valist);
va_end(valist);
return;
}
测试结果:
int main(void)
{
Debugoutput("here are some info to show. your name:%s, your age:%d, your birth:%s, your home:%s.\n",
"lily", 21, "1998-02-14", "Shanghai-China");
return 0;
}
here are some info to show. your name:lily, your age:21, your birth:1998-02-14, your home:Shanghai-China.