用自定义条件包装 printf

Wrap printf with custom condition

我只想在某些条件为真时打印。我知道 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 标准 - 但我们可以尝试一下。

您可以使用 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;
}