user2052436
user2052436

Reputation: 4765

Silencing stdout/stderr

What is a C equivalent to this C++ answer for temporarily silencing output to cout/cerr and then restoring it?

How to silence and restore stderr/stdout?

(Need this to silence noise from 3rd party library that I am calling, and to restore after the call.)

Upvotes: 2

Views: 828

Answers (2)

William Pursell
William Pursell

Reputation: 212544

This is a terrible hack, but should work:

#include <stdio.h>
#include <unistd.h>


int
suppress_stdout(void)
{
    fflush(stdout);
    int fd = dup(STDOUT_FILENO);
    freopen("/dev/null", "w", stdout);
    return fd;
}

void
restore_stdout(int fd)
{
    fflush(stdout);
    dup2(fd, fileno(stdout));
    close(fd);
}

int
main(void)
{
    puts("visible");
    int fd = suppress_stdout();
    puts("this is hidden");
    restore_stdout(fd);
    puts("visible");
}

Upvotes: 3

codyne
codyne

Reputation: 552

#include <stdio.h>

#ifdef _WIN32
#define NULL_DEVICE "NUL:"
#define TTY_DEVICE "COM1:"
#else
#define NULL_DEVICE "/dev/null"
#define TTY_DEVICE "/dev/tty"
#endif

int main() {
    printf("hello!\n");

    freopen(NULL_DEVICE, "w", stdout);
    freopen(NULL_DEVICE, "w", stderr);

    printf("you CAN'T see this stdout\n");
    fprintf(stderr, "you CAN'T see this stderr\n");

    freopen(TTY_DEVICE, "w", stdout);
    freopen(TTY_DEVICE, "w", stderr);

    printf("you CAN see this stdout\n");
    fprintf(stderr, "you CAN see this stderr\n");
    return 0;
}

Upvotes: 1

Related Questions