Disable printf using freopen stdout while keeping std::cout functioning

Viewed 155

I have a piece of code that takes an ostream as input, which can be std::cout or a std::sstream and outputs to it.

void myFunction(std::ostream out)
{
    out << "output";
}

At the same time I want to disable the use of printf to any third party library, so that they do not interfere with my output in case out == std::cout. I can achieve this by using freopen to redirect stdout to NUL, but this prevents my code to correctly print to std::out.

Is it there a way to redirect only printf while keeping std::cout functioning?

My current solution is as follows, but the function is not agnostic of the type of out anymore.

void myFunction(std::ostream out)
{
    unlockStdout();  // redirect stdout to the original stdout
    out << "output";
    lockStdout(); // redirect stdout to NUL
}
1 Answers

Im pretty sure this is not possible (at least using standard c/c++/posix). This is because printf is using STDOUT directly - the lower level. Once you redirect STDOUT it is "game over" so to speak (again: unless you go beyond standard).

You can do the opposite if you want to - that is redirect just std::cout without redirecting printf.

Related