Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to temporarily suppress output from printf?

Tags:

c++

linux

In a console application I am calling a library function that outputs some messages (probably using printf) that I am not interested in:

void libFoo()
{
    // does some stuff
    printf("boring message");
    // does some more stuff
}

I tried suppressing cout before which didn't work, hence why I think libFoo is using printf:

cout << "interesting messsage" << endl;
streambuf* orig_buf = cout.rdbuf();
cout.rdbuf(NULL);
libFoo();
cout.rdbuf(orig_buf);
cout << "another interesting messsage" << endl;

This code outputs all these messages. Is there a way to temporarily suppress output from printf? I am using Linux Mint.

like image 687
gornvix Avatar asked Dec 03 '25 21:12

gornvix


1 Answers

Here it is:

int supress_stdout() {
  fflush(stdout);

  int ret = dup(1);
  int nullfd = open("/dev/null", O_WRONLY);
  // check nullfd for error omitted
  dup2(nullfd, 1);
  close(nullfd);

  return ret;
}

void resume_stdout(int fd) {
  fflush(stdout);
  dup2(fd, 1);
  close(fd);
}

If this is C++, also flush cout for good measure.

EDITED TO CLARIFY

The fd you pass to resume_stdout is the same one you received as supress_stdout's return value.

like image 148
Shachar Shemesh Avatar answered Dec 05 '25 09:12

Shachar Shemesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!