home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!ferkel.ucsb.edu!taco!rock!stanford.edu!agate!spool.mu.edu!sdd.hp.com!ux1.cso.uiuc.edu!news.cso.uiuc.edu!osiris.cso.uiuc.edu!gordon
- From: gordon@osiris.cso.uiuc.edu (John Gordon)
- Subject: Re: getch
- References: <1992Nov13.022217.13742@pasteur.Berkeley.EDU>
- Message-ID: <BxrqH2.KMH@news.cso.uiuc.edu>
- Sender: usenet@news.cso.uiuc.edu (Net Noise owner)
- Organization: University of Illinois at Urbana
- Date: Sun, 15 Nov 1992 17:41:24 GMT
- Lines: 81
-
- c60c-2gf@web-2a.berkeley.edu () writes:
-
-
- >At home, I run a version of Turbo C on my IBM. There is a library function
- >with a prototype in conio.h called getch (and getche). Is there an
- >equivalent of this function on standard Unix systems. I'm on a Sun, I
- >believe (not a Sparc station though). This question may be really
- >obvious, but I am not quite sure how all the specifics with input/output
- >work on the system (i.e. x-window control etc.) and I can't quite seem
- >to find getch. The man page goes on and on abou'curses,' but I am still
- >pretty lost. Any help would be appreciated (in email, please). Thanks
-
- The function you want is getchar(). Unfortunately, in the default
- mode of most (all?) terminals, getchar() will not return a value until
- ENTER has been pressed. Fortunately, you can change the mode of the
- terminal so that it will read 1 character without waiting for ENTER. (This
- is called "raw mode", and the default is "cooked mode", if you care.)
-
- Here is a function that works for me. It runs under DYNIX/ptx,
- which is a POSIX-compliant variant of UNIX SYSV. If you are running
- under a Berkeley-type UNIX, it might need some changing. Anyway, here's
- the function:
-
- ------------------------------------------------
- /*
- Getkey.c
-
- Written 01/16/1991 by John Gordon, adapted from code supplied by Tim Evans
-
- The purpose of this program is to set ioctl to "raw" mode, read a keypress,
- reset the ioctl mode, and return the character read.
-
- History:
- 01/16/91 by John Gordon - initial version adapted from Tim's code
- */
-
- #include <termio.h>
- #include <stdio.h>
- #include <string.h>
-
- int getkey()
- {
- int c;
- struct termio tsav, tchg;
-
- if (ioctl(0, TCGETA, &tsav) == -1)
- {
- perror("getkey: can't get original settings");
- exit(2);
- }
-
- tchg = tsav;
-
- tchg.c_lflag &= ~(ICANON | ECHO);
- tchg.c_cc[VMIN] = 1;
- tchg.c_cc[VTIME] = 0;
-
- if (ioctl(0, TCSETA, &tchg) == -1)
- {
- perror("getkey: can't initiate new settings");
- exit (3);
- }
-
- c = getchar();
-
- if(ioctl( 0, TCSETA, &tsav) == -1)
- {
- perror("getkey: can't reset original settings");
- exit(4);
- }
-
- return(c);
-
- } /* end getkey() */
- ------------------------------------------------
-
- Enjoy.
-
- ---
- John Gordon My incredibly witty saying has been
- gordon@osiris.cso.uiuc.edu Politically Corrected into oblivion.
-