Home > Enterprise >  Silencing stdout/stderr
Silencing stdout/stderr

Time:12-16

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

How to set fail-state to stderr/stdout?

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

CodePudding user response:

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));
}

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

CodePudding user response:

#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;
}
  •  Tags:  
  • c c
  • Related