【问题标题】:Wrap printf with custom condition用自定义条件包装 printf
【发布时间】:2019-09-18 01:34:53
【问题描述】:

如果某些条件为真,我只想 printf。我知道 printf 是一个可变参数函数,但遗憾的是我似乎在这里找不到任何解释我可以包装它的线程。

基本上在我要写的代码中:

printf(" [text and format] ", ... args ...);

我想写一些类似的东西

my_custom_printf(" [text and format] ", ... args ...);

然后是这样实现的:

int my_custom_printf(const char* text_and_format, ... args ...)
{
    if(some_condition)
    {
        printf(text_and_format, ... args...);
    }
}

条件的第一个版本将独立于 args(它将位于某个全局变量上),但它可能在未来成为需要的条件一个参数。

无论如何,现在我只需要原型中... args ... 的语法和my_custom_printf 的正文。

我正在使用 GCC,但我不知道哪个 C 标准 - 但我们可以尝试一下。

【问题讨论】:

标签: c printf customization variadic-functions


【解决方案1】:

你可以使用vprintf:

#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>

static bool canPrint = true;

int myprintf(const char *fmt, ...)
{
    va_list ap;
    int res = 0;

    if (canPrint) {
        va_start(ap, fmt);
        res = vprintf(fmt, ap);
        va_end(ap);
    }
    return res;
}

int main(void)
{
    myprintf("%d %s\n", 1, "Hello");
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多