c++command-linestdoutcoutoutput-redirect

Should command line redirecting of stdout always redirect cout too?


I am not clear on whether redirecting stdout to a file from the command line should also always redirect cout (and similarly for stderr and cerr).

As a test I wrote the code below. My understanding is that with the argument of sync_with_stdio set to true, which is the default, cout will stream its output to stdout, in which case redirecting stdout will redirect cout too, and that is what happened when using VS on my Win10 machine.

However, when I changed the argument to false all three outputs still got redirected. I halfway expected that only the printf output would get redirected and the cout outputs would still get displayed.

An explanation of what is going on would be appreciated since I'm obviously missing something. Thanks!

#include <iostream>
int main()
{
   std::ios::sync_with_stdio(false);
   std::cout << "a\n";
   std::printf("b\n");
   std::cout << "c\n";
}

Solution

  • You misunderstand what sync_with_stdio means. It’s completely unrelated to redirection, it only concerns synchronisation between the two streams. If the set to false, the two streams may be buffered independently.

    But in the end both streams write to the standard output file descriptor. The same is true for stderr and (for reading) stdin.

    If you want to redirect std::cout, you need to reset its stream buffer via rdbuf.