C - How to suppress a sub function's output? C - How to suppress a sub function's output? c c

C - How to suppress a sub function's output?


You can save the global variable stdout before bar();, then set it to /dev/null, then restore it. Code example;

#include <stdio.h>int main() {    int old_stdout = dup(1);    freopen ("/dev/null", "w", stdout); // or "nul" instead of "/dev/null"    printf("asd1");    fclose(stdout);    stdout = fdopen(old_stdout, "w");     printf("asd2");    return 0;}

Tested on OS X, not sure about Windows.

EDIT: You can replace /dev/null with nul on Windows. As for the fdopen() and dup() working under Windows - they're part of the POSIX.1 standard according to my man pages, but I haven't tested it.

EDIT 2: As suggested in the comments, if the solution does not work for Windows, there's another suggestion in this SO answer.

EDIT 3: A longer, though standard compliant and cross-platform way to do this is as following. (code adapted from mentioned SO question, and Microsoft's documentation for _dup)

#include <stdio.h>#ifdef _WIN32#include <io.h>char * const nulFileName = "NUL";#define CROSS_DUP(fd) _dup(fd)#define CROSS_DUP2(fd, newfd) _dup2(fd, newfd)#else#include <unistd.h>char * const nulFileName = "/dev/null";#define CROSS_DUP(fd) dup(fd)#define CROSS_DUP2(fd, newfd) dup2(fd, newfd)#endifint main() {    int stdoutBackupFd;    FILE *nullOut;    /* duplicate stdout */    stdoutBackupFd = CROSS_DUP(STDOUT_FILENO);    fflush(stdout);    nullOut = fopen(nulFileName, "w");    CROSS_DUP2(fileno(nullOut), STDOUT_FILENO);    printf("asd1\n");    fflush(stdout);    fclose(nullOut);    // Restore stdout    CROSS_DUP2(stdoutBackupFd, STDOUT_FILENO);    close(stdoutBackupFd);    printf("asd2\n");    return 0;}

The flushes are required to make sure that (1) anything printed before switching stdout is indeed printed to screen, and (2) nothing that was printed before switching back stdout to console (or pipe) is printed.