[prog] reading backspace key

Akkana Peck akkana at shallowsky.com
Sun Feb 8 16:35:46 EST 2004


> On Sun, Feb 08, 2004 at 03:01:54PM -0600, ed orphan wrote:
> > This is bizzare. I can't find a C function 
> > that will read in a backspace keys from the
> > keyboard. 

Cliff Crawford writes:
> getchar() can do this, but you need to set your terminal so that it
> immediately sends all keypresses to your program, rather than
> buffering them until the user presses Return (which is the default
> behavior).  I don't remember exactly how to do this, but the man page

To save you some time (it actually takes a fair amount of man page
reading to collect all the pieces), here's a snippet of code I used
in a meteor-counting program:

int InitTerminal()
{
    struct termios termios;
    if (tcgetattr(0, &termios) != 0) {
        perror("Couldn't get terminal modes!\n");
        return -1;
    }
    termios_sav = termios;
    cfmakeraw(&termios);
    if (tcsetattr(0, TCSANOW, &termios) != 0)
    {
        perror("Couldn't set raw mode!\n");
        return -1;
    }
    return 0;
}

void ResetTerminal()
{
    tcsetattr(0, TCSANOW, &termios_sav);
}

Be sure to call ResetTerminal on all possible exits from the program
(you probably want to catch signals like SIGINT and so forth, if
possible) since you don't want your terminal in raw mode after
you exit.  If you get there accidentally, use the "reset" command
to fix it.

	...Akkana


More information about the Programming mailing list