封装一个可变参数打印函数

13 篇文章 0 订阅

在开发中,经常会用到打印,而这些打印在程序运行阶段不需要,仅在调试或开启现象的时候需要,我们用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.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值