• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

184
Views
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.)

about 3 years ago · Santiago Trujillo
2 answers
Answer question

0

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");
}
about 3 years ago · Santiago Trujillo Report

0

#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;
}
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error