Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

c++ - How to disable printf function?

I have three files as below

Test.cpp

void helloworld()
{
    disable pf;
    pf.Disable();
    printf("No statement 
");
    }
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();
};

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can disable the printf ouput by:

close(STDOUT_FILENO);

or you can use also:

fclose(stdout);

This will disable all output to the stdout

Example:

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

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

Note

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...