On Sat, Aug 02, 2003 at 09:20:35AM -0500, Benjamin J. Weiss wrote:
> On Sat, 2 Aug 2003, Buz Davis wrote:
> > I would like a routine to read the keyboard and report the single key
> > pressed, and give me control back without waiting for ENTER to be pressed.
> > ...
> 
> Okay, this is going to be an unorthodox answer, but it may get you where 
> you need to go...
> <<BIOS read recommended>> 
> ...
> Of course, you'd have no portability....

To put it mildly...

You're interacting with the stdio library.  Use 'getc'--do "man getc"--for
single-character input.  Since terminal input is line buffered, you will
have to make a call to 'setbuf'.

HOWEVER, if you're on Unix/Linux, you'll also have to turn off buffering
in the tty driver.  This involves a call to tcgetattr, clearing at
least ICANON, in the c_lflag element, and then a call to tcsetattr.
(This will still show the input character being echoed; you'll have to
separately turn that off.)  Man 'termios' for all this.

It sounds uglier than it is--the following really stupid example shows
how to do it.  You should--as I don't here--check return values, etc.
(FOR THE NITPICKERS:  I REPEAT, IT IS A QUICK AND DIRTY EXAMPLE.
DON'T POST OR MAIL TO TELL ME IT SHOULD BE MORE ROBUST...)

        #include <stdio.h>
        #include <termios.h>
        #include <unistd.h>

        int main(int argc, char **argv)
        {
                char foo;
                struct termios krod;

                setvbuf(stdin,NULL,_IONBF,0);

                tcgetattr(fileno(stdin),&krod);
                krod.c_lflag ^= (ICANON|ECHO);
                tcsetattr(fileno(stdin),TCSANOW,&krod);

                for(;;)
                {
                        foo = getc(stdin);
                        printf("Got %c\n", foo);

                        if ( foo == 'x' )
                                break;
                }
        }

Cheers,
-- 
        Dave Ihnat
        [EMAIL PROTECTED]


-- 
redhat-list mailing list
unsubscribe mailto:[EMAIL PROTECTED]
https://www.redhat.com/mailman/listinfo/redhat-list

Reply via email to