[Qt-interest] stdout of MSWin GUI application run from console

Graeme Gill graeme2 at argyllcms.com
Wed Apr 13 18:04:08 CEST 2011


Scott Aron Bloom wrote:
> Couple of issues I found...
>
> The fileno(stdout) (and the others) is already set by the time main is
> called...  I created a TRIVIAL Qt GUI based app..
>
> If I call the app>  foo, to redirect the stdout to the foo.  It works
> like a charm, WITHOUT your code...

This might be compiler dependent I guess. I was using MingW.

> If I use your code and force a reopen, the>  breaks and the output only
> goes to the console

In my tests I do the AttachConsole straight after main(),
and the test of _fileno(stdout) == -1 (Note there is a typo in
the code I posted - _fileno(stderr) was repeated) to ensure that
stdio wasn't freopen()'s if it had been redirected.

Graeme Gill.

- - - - - - - - - - - - - - - - - - - -

#include <QApplication>
#ifdef Q_WS_WIN
#include <windows.h>
#endif // Q_WS_WIN
#include <stdio.h>

#include "tdialog.hpp"

int main(int argc, char *argv[]) {

#ifdef Q_WS_WIN
     {
         BOOL (WINAPI *AttachConsole)(DWORD dwProcessId);

         *(FARPROC *)&AttachConsole =
           GetProcAddress(LoadLibraryA("kernel32.dll"), "AttachConsole");

             if (AttachConsole != NULL && AttachConsole(((DWORD)-1))) {
                 if (_fileno(stdout) == -1)
                     freopen("CONOUT$","wb",stdout);
                 if (_fileno(stderr) == -1)
                     freopen("CONOUT$","wb",stderr);
                 if (_fileno(stdin) == -1)
                     freopen("CONIN$","rb",stdin);
             }
     }
#endif // Q_WS_WIN

     printf("Hi there!\n");

     QApplication app(argc, argv);

     TDialog *dialog = new TDialog;

     dialog->show();

     return app.exec();
}



More information about the Qt-interest-old mailing list