Should command line redirecting of stdout always redirect cout too?

183 Views Asked by At

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";
}
2

There are 2 best solutions below

0
Konrad Rudolph On BEST ANSWER

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.

0
463035818_is_not_an_ai On

From cppreference (emphasize mine):

The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stdout.

sync_with_stdio:

Sets whether the standard C++ streams are synchronized to the standard C streams after each input/output operation.

std::cout always writes to stdout.