Question on implementing "repeat...until keypress"?

robert at arizona.UUCP robert at arizona.UUCP
Wed Feb 4 06:15:49 AEST 1987


In article <32100 at auc.UUCP>, maw at auc.UUCP (Michael A. Walker) writes:
> I have some experience in using Apple Pascal(using the UCSD Pascal) and I
> have used a loop that will continue until either a defined key or any
> key is pressed on the keyboard.  
> 

The following works under Berkeley 4.3; detects any key press.  To
have it detect a particular key, it could do a get character and
see if that's the one of interest.

#include	<stdio.h>
#include	<sgtty.h>
#include	<sys/time.h>

typedef	char	bool;
#define TRUE	1
#define	FALSE	0


main()
{
  int i = 0;

  flip(); /* first call puts terminal in raw/noecho mode */

  do {

    printf("Hello <%d>\r\n", i++);  /* just to have something to do here */

  } while (!keypressed());

  flip(); /* second call puts terminal back in original mode */

}  /* main */


/* flip
     Simple routine to switch back and forth between raw and
     regular modes.
*/
flip()
{
  struct sgttyb ttyb;

  ioctl(0, TIOCGETP, &ttyb);
  ttyb.sg_flags ^= (RAW | ECHO);
  ioctl(0, TIOCSETP, &ttyb);

}  /* flip */


/* keypressed
     Returns TRUE if any key is pressed.  Assumes terminal is
     in raw/no echo mode.
*/
bool keypressed()
{
  static struct timeval timeout = {0, 0};
  static int rfd, wfd, efd;

  rfd = 1 << 0; /* this zero refers to device 0 (stdin) */
  wfd = efd = 0;

  return select(32, &rfd, &wfd, &efd, &timeout);

}  /* keypressed */



More information about the Comp.lang.c mailing list