printf, data presentation

John B Scalia jb at aablue.UUCP
Sat Jan 7 11:00:18 AEST 1989


In <8332 at ihpl.ATT.COM> Mike Knudsen makes a request for an INKEY type of
function similar to what is found in most BASICs.

The following code should solve your problem. It allows an INKEY() type
function that allows for multiple returns (ie. function keys), timeout if
user does not press a key, and the ability to wait forever if delay is given
as 0 :-) and the user must make some input. It will also trap every keyboard
stroke I've ever managed to give it. (At least I've not had a problem.)

--------- Cut here ----------
#include <termio.h>
#include <ctype.h>

int key_ret(deft, work)			/* Generic Keyboard input like inkey */
int 	deft;				/* Number of seconds to delay */
char	work[];				/* character string to return result */
{
	struct termio oldterm, curterm;
	int	timer, ret_code;

	timer = deft * 10;		/* timer = # of seconds to wait */

	if (ioctl (0, TCGETA, &curterm) == -1)
		return(-1);		/* Not a terminal, abort */

	oldterm = curterm;

	curterm.c_lflag &= ~ICANON;	/* canonical processing off */

	if (timer == 0)
		curterm.c_cc[VMIN] = 1;
	else {
		curterm.c_cc[VTIME] = timer;
		curterm.c_cc[VMIN] = 0;
	}
	ioctl (0, TCSETA, &curterm);

	ret_code = read (0, work, 10);

	ioctl (0, TCSETA, &oldterm);	/* restore terminal to old settings */
	return (ret_code);
}
# End of function ----------------------

This works only if your function or definable keys produce less than 10
characters, of course you may change this to any number you'd want at the
read(n,C,10) statement. Please no flames about style, etc. I wrote this so
long ago I almost forgot where in fact I had put it.



More information about the Comp.lang.c mailing list