简体   繁体   中英

How to temporarily suppress output from printf?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM