I want to call bar() in foo(), bar() will change some global variables’ values(this is what I want), but meanwhile produce some output( I dont’ want any output);
void foo()
{
//I have tried:
//system("1>&/dev/null") and of course this won't work
bar();
}
What can I do to suppress bar()‘s output?
You can save the global variable
stdoutbeforebar();, then set it to/dev/null, then restore it. Code example;Tested on OS X, not sure about Windows.
EDIT: You can replace
/dev/nullwithnulon Windows. As for thefdopen()anddup()working under Windows – they’re part of the POSIX.1 standard according to mymanpages, 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)
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.