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

plocher at puff.UUCP plocher at puff.UUCP
Mon Feb 2 14:47:34 AEST 1987


Question asked about implementing above loop on a 3bx w/SV:

  You mentioned curses.  If you are already using it, there is a 
  function called nodelay(win, flag) which causes getch() to
  return -1 if no input is ready.
   
       #include <curses.h>
	 ...
	 int ch;
	 ...
	 initscr();
	 ...
	 nodelay(curscr, TRUE);
	 while ( (ch = getch()) == -1) {
	     /* do this while waiting for a character */
         }
         /* at this point, ch contains char typed */
  
  If you are not using curses (no reason to use it just for the above!)
  then you might look at the termio(7) man pages where they describe
  ioctl()s which set character count/timeout periods for input.  (This
  is what nodelay() does internally)

  The following was posted to the net a while back; I've used the
  ideas in a few of my programs, and they work ok.
	   Have fun!
	     John


-------- NOT A SHAR ---------

/*
 * In article <30896 at arizona.UUCP>, sbw at arizona.UUCP (stephen wampler) writes:
 * > What is the preferred way to determine if a key has been pressed
 * > on the keyboard when running UNIX Sys V?  I know that some UN*X ...
 * -- 
 * Stuart D. Gathman	<..!seismo!{vrdxhq|dgis}!BMS-AT!stuart>
 */

#include <sys/termio.h>

{
  struct termio tty, save;
  char c;

  ioctl(0,TCGETA,&tty);
  save = tty;				/* save current tty definitions */
  tty.c_lflag &= ~(ECHO|ICANON);	/* enter raw mode */
  tty.c_cc[VMIN]=0;		/* wait for at least VMIN chars on read */
  tty.c_cc[VTIME]=0;		/* wait at least VTIME seconds/10 on read   ioctl(0,TCSETA,&tty);

  saved = read(0,&c,1);
  if (saved)
    printf("You typed a '%c'.\n",c);
  else
    printf("You haven't typed anything yet.\n");

/*
  Note, you will have to save 'c' yourself if you need it!
  Perhaps stdio would work (using ungetc()).
*/

/* restore tty state */

  ioctl(0,TCSETA,&save);
}



More information about the Comp.lang.c mailing list