Playing with the Windows standard input and output (keyboard and monitor screen) handles
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows Xp Pro SP2
Target platform: none, just for learning and fun
Header file: Standard and Windows
Additional library: Windows Platform SDK
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: non-CLR or unmanaged.
To do: Playing with standard input and output handles in Win32 programming
To show: Various Windows threads and processes functions
// For WinXp
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
#define BUFSIZE 4096
int main(void)
{
CHAR chBuf[BUFSIZE];
DWORD dwRead, dwWritten;
HANDLE hStdin, hStdout;
BOOL fSuccess;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
hStdin = GetStdHandle(STD_INPUT_HANDLE);
// Verify
if ((hStdout == INVALID_HANDLE_VALUE) || (hStdin == INVALID_HANDLE_VALUE))
// Exit with error...
ExitProcess(1);
else
printf("GetStdHandle() for standard input and output is OK.\n");
for (;;) // May use other program control here to stop automatically :o)
{
// Read from standard input.
fSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);
if (!(fSuccess || dwRead == 0))
{
printf("ReadFile(), from standard input failed.\n");
break;
}
else
printf("ReadFile(), from standard input is OK.\n");
// Write to standard output...
fSuccess = WriteFile(hStdout, chBuf, dwRead, &dwWritten, NULL);
if (!fSuccess)
{
printf("WriteFile(), to standard output failed.\n");
break;
}
else
printf("WriteFile(), to standard output is OK.\n");
}
return 0;
}
Output example:
GetStdHandle() for standard input and output is OK.
This is a sample line of text, from standard input
ReadFile(), from standard input is OK.
This is a sample line of text, from standard input
WriteFile(), to standard output is OK.
This is another sample string from standard input...keyboard
ReadFile(), from standard input is OK.
This is another sample string from standard input...keyboard
WriteFile(), to standard output is OK.
Please press Ctrl+C to stop
ReadFile(), from standard input is OK.
Please press Ctrl+C to stop
WriteFile(), to standard output is OK.
ReadFile(), from standard input is OK.
WriteFile(), to standard output is OK.
^CPress any key to continue . . .