Hello,
The following mentionned code within the PellesC CHM help seems to work but getchar() seems not to work if i compile this code into a Windows project...
Does anyone has an idea please ?
#include <stdio.h>
#include <string.h>
#include <io.h>
#include <windows.h>
void RedirectStdOut(void);
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow )
{
RedirectStdOut();
printf( "zz" );
getchar(); // WHY this does not work ?
return 0;
}
void RedirectStdOut(void)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
// Try creating a new console window.
if (!AllocConsole()) return;
// Set the screen buffer to be larger than normal.
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
csbi.dwSize.Y = 1000; // any useful number...
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csbi.dwSize);
}
// Redirect "stdout" to the console window.
fclose(stdout);
setbuf(stdout, NULL);
FILE *fp = fdopen(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0), "w");
*stdout = *fp;
}
Thanks for anyhelp :)
I believe it's because stdout has been redirected to the new console, but stdin hasn't. getchar is returning EOF and, if you call it, ferror(stdin) is returning true.
INFO: Calling CRT Output Routines from a GUI Application (http://support.microsoft.com/kb/q105305/)
Later:
For some reason, _getch works OK. So I'm not sure about it now.
The same thing happens in Visual C/C++ 2003.
Gerome,
you can find an example of redirection for stdin, stdout and stderr in my code at http://smorgasbordet.com/phpBB2/viewtopic.php?t=726 in the cgi redirection handling. It works well becouse is directly derived from M$ example code (I included full M$ comments).
Hi,
Thanks for your help :)
Here is my functional code this time with getchar() working :)
#include <stdio.h>
#include <io.h>
#include <windows.h>
#include <fcntl.h>
#include <conio.h>
void RedirectStd(void);
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow )
{
RedirectStd();
printf( "\nType any key to continue...\n" );
getchar();
return 0;
}
void RedirectStd(void)
{
int hCrt = -1;
FILE *hf = NULL;
int i = -1;
AllocConsole();
hCrt = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
hf = _fdopen(hCrt, "w");
*stdout = *hf;
i = setvbuf(stdout, NULL, _IONBF, 0);
printf( "stdout//" );
hCrt = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
hf = _fdopen(hCrt, "r");
*stdin = *hf;
i = setvbuf(stdin, NULL, _IONBF, 0);
printf( "stdin//" );
hCrt = _open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT);
hf = _fdopen(hCrt, "w");
*stderr = *hf;
i = setvbuf(stderr, NULL, _IONBF, 0);
printf( "stderr//" );
}
Thanks for posting the working example. I tried to do the same thing but I couldn't get stdin to work. I was opening stdin for write intead of read. :roll: