用自定义条件包装 printf

Cha*_*les 3 c customization printf variadic-functions

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

基本上我写的代码中的每一个:

printf(" [text and format] ", ... args ...);
Run Code Online (Sandbox Code Playgroud)

我想写一些类似的东西

my_custom_printf(" [text and format] ", ... args ...);
Run Code Online (Sandbox Code Playgroud)

然后是这样实现的:

int my_custom_printf(const char* text_and_format, ... args ...)
{
    if(some_condition)
    {
        printf(text_and_format, ... args...);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Dav*_*eri 5

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

274 次

最近记录:

6 年,9 月 前