Reputation: 3384
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.
Upvotes: 3
Views: 2823
Reputation: 8603
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.
Upvotes: 1