How to Redirect Stdout to Some Visible Display in a Windows Application

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



Leave a reply



Submit