Trying to redirect stdout and stderr on Windows - _fileno(stdout) returning -2
Unlike Unix-type systems, in Windows a console application and a GUI application are two different things. GUI applications don't have the concept of stdin, stdout or stderr - they only know about windows, textboxes etc.
The documentation for _fileno says:
If stdout or stderr is not associated with an output stream (for
example, in a Windows application without a console window), the file
descriptor returned is -2.
So if you want to use stdout and stderr, you need to build your application as a console application (you can still use a GUI).
An alternative method is to carry on building the application as a GUI, but allocate a console by calling AllocConsole() at the very start of your application (i.e. the first thing you do in WinMain()
) and then associate the stdout and stderr files:
if(AllocConsole()){
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
How to redirect standard output to output window from Visual Studio
Straightforward standard output redirection will not work, as there is no handle corresponding to OutputDebugString. However, there should be a way:
It could be done by redirecting standard output to a pipe, and then creating a thread which would read the pipe and print anything read from it using OutputDebugString.
Note: I was contemplating for a long ago to implement this, as I am facing exactly the same problem as you do (some libraries using printf or fprintf(stderr....). However, I never really did this. I have always ended modifying the libraries instead, and therefore I do not have a working implementation, but I think it should be feasible in principle.
Temporarily capture stdout of a console app in Windows
Take a look at the SetStdHandle Win32 API. Also, _dup and _dup2 are available.
EDIT
See the following StackOverflow posts.
Redirect stdout to an edit control (Win32)
practical examples use dup or dup2
Related Topics
C++ Inlining Class Methods Causes Undefined Reference
Are C++ Enums Signed or Unsigned
How to Correctly and Standardly Compare Floats
Why Catch an Exception as Reference-To-Const
Why Can't Static_Cast Be Used to Down-Cast When Virtual Inheritance Is Involved
Difference in Performance Between Msvc and Gcc for Highly Optimized Matrix Multplication Code
Why Can't a Derived Class Call Protected Member Function in This Code
Why Is Allocator::Rebind Necessary When We Have Template Template Parameters
Know If .Lib Is Static or Import
How to Read-Write Into/From Text File with Comma Separated Values
C++11 Initializer List Fails - But Only on Lists of Length 2
Calling a Function for Each Variadic Template Argument and an Array
Global Scope VS Global Namespace
C++ Where to Initialize Static Const
Random Number C++ in Some Range