如何禁用printf功能?

Ras*_*yak 2 c++ printf

我有三个文件如下

Test.cpp

void helloworld()
{
    disable pf;
    pf.Disable();
    printf("No statement \n");
    }
int main()
{
    disable dis;
    helloworld();
    printf("Hello World");
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

disable.cpp

    #include "StdAfx.h"
    #include "disable.h"
    disable::disable(void)
    {#define printf(fmt, ...) (0)}
    disable::~disable(void)
   {}
   void disable::Disable()
   {
    #define printf(fmt, ...) (0)
    }
Run Code Online (Sandbox Code Playgroud)

disable.h

#pragma once
class disable
{
public:
    disable(void);
    ~disable(void);
    void Disable();
};
Run Code Online (Sandbox Code Playgroud)

执行后,我得到输出为No Statement Hello World.但我想two printf statements通过调用Disable function和禁用它们disable constructor..请帮助我为什么它不工作以及如何解决这个问题.请帮忙.

但是,如果我愿意,事情就可以了

main()
{
#define printf(fmt, ...) (0)
printf("Hello World");
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我从函数中调用它,为什么不呢?

MOH*_*MED 6

您可以通过以下方式禁用 printf 输出:

close(STDOUT_FILENO);
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用:

fclose(stdout);
Run Code Online (Sandbox Code Playgroud)

这将禁用所有输出到标准输出

例子:

#include<stdio.h>
#include<stdlib.h>

int main(){
    printf ("This message will be displayed\n");
    fclose(stdout);
    printf ("This message will not be displayed\n");
    // to reopen the stdout, this is another question
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

笔记

如果您在程序中使用套接字,那么在这里必须小心,因为 stout 的关闭会导致输出重定向到套接字


Kar*_*k T 5

宏不遵守范围规则,c ++语法规则或任何其他内容.它只是一个文本替换引擎.

当你说#define printf(fmt, ...) (0)disable.cpp,它仅被定义在disable.cpp.如果你要写入disable.h,它将在包含from的所有文件中定义disable.h.

控制宏的唯一方法是使用宏(#if和#ifdef及其同类).因此,您希望通过以下方式实现.

#define DISABLE_PRINTF

#ifdef DISABLE_PRINTF
    #define printf(fmt, ...) (0)
#endif
Run Code Online (Sandbox Code Playgroud)

但这将是一个全局禁用,只能通过注释掉第一个#define并重新编译代码来撤消.没有办法使用宏进行基于选择性/范围的禁用控制.

编辑:printf建议编写一个printf为此目的定义的包装器,而不是重新定义自身.