Unix Routines

mike at bria.UUCP mike at bria.UUCP
Mon Jan 14 15:21:17 AEST 1991


In article <26284 at uflorida.cis.ufl.EDU> Patrick Martin writes:
>Could someone tell me how to do the following on a Unix System:

[ asks question about grabbing cursor keys, clearing the screen, etc. ]

This really belongs in comp.unix.programmer, but anyway ...
UNIX has a standard library called 'curses' which deals with screen
management and has reasonable optimization.  The fundamental concept
in curses is that you are working within a window, and that window
has various attributes.  How those attributes are translated into
actual output to your terminal is via a terminal capability database.
There are two flavors of database, the orginal being 'termcap' developed
at UC Berkeley.  The other flavor is 'terminfo' developed at AT&T, and
is a "compiled" database (termcap is a text file).  The good news is that
terminfo has compatability hooks with termcap, so you don't have to
worry too much about which implementation your system uses, unless you
*really* want to get down and dirty.

Here is a little chunk of code to do what you asked about:

#include <stdio.h>
#include <curses.h>

main()
{
char	*id;
int	c;

	initscr();
	cbreak();
	noecho();
	keypad(stdscr,TRUE);
	clear();
	refresh();

	while ( (c = getch()) != 27 ) {
		switch ( c ) {
			case KEY_UP:	id = "up"; 	break;
			case KEY_DOWN:	id = "down"; 	break;
			case KEY_LEFT:	id = "left"; 	break;
			case KEY_RIGHT: id = "right"; 	break;
			default:	id = "not special"; break;
			}
		mvprintw(0,0,"key press was %s",id);
		clrtoeol();
		refresh();
		}

	endwin();
}

Note a few things:

	1. The program begins with initscr(), which initializes the curses
	   environment, and is required.

	2. keypad(stdscr,TRUE) enables "keypad" mode, which is required
	   for curses to detect "special" keys, such as arrow keys and
	   function keys.  Cbreak() and noecho() are also useful when
	   you're doing this kind of work ...

	3. refresh() is used to cause the window buffer to be written to
	   the screen (think of it kind of like an fflush()); use it often.

	4. you'll notice that 'c' is of type int, *not* char.  Declaring
	   it as a char will have unpredictable results (and certainly won't
	   be what you want it to be).

	5. endwin() terminates the curses environment, and is required,
	   otherwise your terminal will be in a rather funky state (to
	   get back to normal, should this happen, enter the command:

			stty sane

	   and press the CTRL-J key (not the enter key, it probably won't
	   work for you).

Dig up some UNIX programming references, and look for the curses manual
pages.  All will be revealed.
-- 
Michael Stefanik, Systems Engineer (JOAT), Briareus Corporation
UUCP: ...!uunet!bria!mike
--
technoignorami (tek'no-ig'no-ram`i) a group of individuals that are constantly
found to be saying things like "Well, it works on my DOS machine ..."



More information about the Comp.lang.c mailing list