如何禁用printf功能? [英] How to disable printf function?

查看:46
本文介绍了如何禁用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;
}

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)
    }

disable.h

#pragma once
class disable
{
public:
    disable(void);
    ~disable(void);
    void Disable();
};

执行后,我得到的输出为 No Statement Hello World .但是我想通过调用 Disable函数 disable构造函数来禁用这两个两条printf语句.请帮助我为什么它不起作用以及如何解决此问题.请帮忙.

After executing, I am getting output as No Statement Hello World. But I would like to disable these two printf statements by calling Disable function and disable constructor.. Please help me why it is not working and how to solve this. Please help.

但是如果我喜欢的话,一切都会很好

But things works fine if I do like

main()
{
#define printf(fmt, ...) (0)
printf("Hello World");
}

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

But why not if I am calling it from a function?

推荐答案

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

You can disable the printf ouput by:

close(STDOUT_FILENO);

或者您也可以使用:

fclose(stdout);

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

This will disable all output to the stdout

示例:

#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;
}

注意

如果您在程序中使用套接字,则此处要格外小心,因为关闭粗壮将导致输出重定向到套接字

If you are using sockets in your program, than you have to be careful here because the close of stout will cause the redirection of the output to the sockets

这篇关于如何禁用printf功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆