Skip to content Accesskey=4Skip to sub-navigation Accesskey=3View our Accessibility Options MIT Information Systems Home About IS&T Contact IS&T Site Map Search Advanced Search
Getting StartedGetting Services by Topic or Alphabetically Getting Help

On This Page

[Help]

  

Quick Links

Top Level

Related Links

Ask OLC a question

Athena Consulting Homepage

Helpdesk Stock Answers (for Mac/PC questions)


CHARACTER-AT-A-TIME input in C

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

MIT Home | Getting Started | Getting Services | Getting Help | About IS&T | Accessibility
Ask a technology question or send a comment about this web page.