Search code examples
c++windowsstderr

How to associate stderr with output stream


When I try to get file descriptor for stderr with fileno(stderr), the result is -2 instead of 2. The documentation for fileno says that that is probably because in a Windows application without a console window stderr is not associated with an output stream.

I need stderr file descriptor because I would like to redirect stderr to pipe using _dup2(), so everything written with fprintf(stderr, "...") and std::cerr << "..." will be redirected to the pipe.

My question is if it is possible to get the file descriptor for stderr in gui application, where there is no console window? Can I somehow open the default stderr file descriptor before calling fileno(stderr)?

EDIT:
I manage to make it work to redirect fprintf(stderr, "...") to pipe by first calling freopen("temp.txt", "w",stderr) and then calling fileno(stderr) to get the file descriptor, based on the idea proposed by @darune.

I wish to do this, because I would like to redirect data from external libraries which are not under my control.


Solution

  • std::cerr can be redirected inside your program, but stderr cannot (at least not in any portable or standard way I am aware about).

    You can first use std::freopen and after that the valid file descriptor can be obtained with std::_fileno(). That may or may not be enough, so if you need anything else to happen after that point, you are stuck with having to monitor the file from inside your own program (eg. ala. tailing the file) and doing your custom handling.