You normally can't read input a character at a time from the terminal.  By
default, the terminal is configured to be in line-by-line mode, so that
the editing characters (like the backspace key) can be used when entering 
a line of text; this is also much more efficient over the network.

The book "Advanced Programming in the UNIX Environment" by W Richard Stevens
(published by Addison Wesley and available at most technical bookstores such
as Quantum Books) has detailed information on terminal i/o among its other
strengths.

Below is an example of how to get character-at-a-time input using C and the
termios structure.

	#include <stdio.h>
	#include <stdlib.h>
	#include <sys/types.h>
	#include <sys/ioctl.h>
	#include <termios.h>
	#include <unistd.h>

	struct termios tty, otty;

	void cbreak(struct termios tty)
	{
	  tty.c_lflag     = tty.c_lflag & ~(ECHO | ECHOK | ICANON);
	  tty.c_cc[VTIME] = 1;
	  tcsetattr(STDIN_FILENO, TCSANOW, &tty);
	}
	
	
	void cooked(struct termios tty)
	{
	  tty.c_lflag     = otty.c_lflag;
	  tty.c_cc[VTIME] = 0;
	  tcsetattr(STDIN_FILENO, TCSANOW, &tty);
	}

	
	int main(int argc, char **argv)
	{
	  int i, j;
	  
	  /* Get original tty settings and save them in otty */
	  tcgetattr(STDIN_FILENO, &otty);
	  tty = otty;
	
	  cbreak(tty);
	
	  for (i=0; i<10; i++) {
	    fprintf(stdout, "Type a character: ");
	    fflush(stdout);
	    j = getchar();
	    fprintf(stdout, "%c\n", j);
	    fflush(stdout);
	  }
	
	  /* Reset to the original settings */
	  tcsetattr(STDIN_FILENO, TCSANOW, &otty);
	  return (0);
	}


Last updated on May 21, 1997
