Redirect IO in win32 GUI application to console

Arek Baranowski praktikant01@panoratio.de
Thu May 6 08:29:00 GMT 2004


Hi folks,
I need a win32 GUI application with standard IO access to a console.
I found at the web a solution (see source at end of this mail) which works fine with windows console (winXP) but crashes when used with the cygwin console. In detail it's the line

  . . .

  *stdout = *fp;

  . . .

which doesn't work.

For some helpful ideas I would appreciate.


___________________________________________

   Dipl.-Informatiker
   Arkadiusz Baranowski

   Panoratio Database Images GmbH
   Ismaninger Str. 17-19
   81675 München

   Tel: +49 89 413 006-82
   Mobil: +49 179 479 451 0
   E-Mail: arek.baranowski@panoratio.de

            www.panoratio.de
___________________________________________






// Beginning of file

// This is required for using win console functions
#define _WIN32_WINNT 0x0501

#include <windows.h>
#include <conio.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>


int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR lpCmdLine,
                     int nCmdShow)
{


  int hConHandle;
  long lStdHandle;
  FILE *fp;
  int iVar;

  // Try to attach to a console
  if (!AttachConsole (ATTACH_PARENT_PROCESS)) {
    MessageBox (NULL,"Could not attach to a console.\n"
                "Start program from a console.",
                "Message Box",MB_OK);
    ExitProcess (1);
  }

  // redirect unbuffered STDOUT to the console
  lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
  hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  fp = _fdopen( hConHandle, "w" );
  *stdout = *fp;
  setvbuf( stdout, NULL, _IONBF, 0 );

  // redirect unbuffered STDIN to the console
  lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
  hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  fp = _fdopen( hConHandle, "r" );
  *stdin = *fp;
  setvbuf( stdin, NULL, _IONBF, 0 );

  // redirect unbuffered STDERR to the console
  lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
  hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  fp = _fdopen( hConHandle, "w" );
  *stderr = *fp;
  setvbuf( stderr, NULL, _IONBF, 0 );

  // test stdio
  fprintf(stdout, "Test output to stdout\n");
  fprintf(stderr, "Test output to stderr\n");
  fprintf(stdout, "Enter an integer to test stdin: ");
  fscanf(stdin,"%d", &iVar);
  printf("You entered %d\n", iVar);
  getch();


  return 0;

}

//End of File


--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Problem reports:       http://cygwin.com/problems.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/



More information about the Cygwin mailing list