Expert C Programming

(Jeff_L) #1

The C compilers from Microsoft and Borland provide getch() (or getche() to echo the character)
to get input character-by-character without waiting for the whole line.


People often wonder why ANSI C didn't define a standard function to get a character if a key has been
pressed. Without a standard function every system has a different method, and program portability is
lost. The argument against providing kbhit() as part of the standard is that it is mostly useful for
games software, and there are many other terminal I/O features that are not standardized. In addition,
you don't want to promise a standard library function that some OS's will find difficult to provide. The
argument for providing it is that it is mostly useful for games software, and that games writers don't
need the myriad of other terminal I/O features that could be standardized. Whichever view you hold,
it's true that X3J11 missed an opportunity to reinforce C as the language of choice for a generation of
student programmers writing games on UNIX.


Handy Heuristic


The Boss Key


Games software is more important than generally thought. Microsoft realizes this, and
thoughtfully provides all their new games software with a "boss key". You hit the boss key
when you notice in the corner of your eye that your manager is sneaking up on you. It
causes the game to instantly disappear, so when the boss strides over to your terminal, it
looks like you were working. We're still looking for the boss key that will collapse MS-
Windows to reveal a proper window system underneath...


On UNIX, there's a hard way and an easy way to get character-by-character input. The easy way is to
let the stty program do the work. Although it is an indirect means of getting what you want, it's trivial
to program.


#include <stdio.h>


main()


{


int c;


/* The terminal driver is in its ordinary line-at-a-time mode


*/


system("stty raw");


/ Now the terminal driver is in character-at-a-time mode /


c = getchar();


system("stty cooked");


/ The terminal driver is back in line-at-a-time mode /

Free download pdf