Read Backspace With getchar()

[ The Easy Way ]


I came across this problem while writing the UNIX shell in this post. I needed a lot of control over user input, including the ability to read the backspace character. Because of the way that a unix console normally handles user input (i.e., buffered), you cant simply read the backspace character with getchar(); in fact, your program doesn't receive any input until the user enters a newline (i.e, presses enter).

The workaround is to change the console input mode to 'raw' with the stty command. In this mode, everything the user types (including backspace) is fed directly to your program, so reading the backspace key is as simple as calling getchar() and comparing the result to the octal ASCII value '\177'. (Note that 177 is actually the octal ASCII value for DEL -- in my experience, this is what most Unix systems actually interpret when you press backspace. If '\177' doest not work for you, try '\010', which is the actual value of backspace.) Here's an example:

C code for Unix-Like Systems:

#include <stdio.h>

int i;

int main(){

        printf("\nPress backspace: ");

	//set input mode to raw and turn echo off
        system("/bin/stty raw");
        system("/bin/stty -echo");

        char c = getchar();

	//set mode back to cooked, and turn echo on
        system("/bin/stty cooked");
        system("/bin/stty echo");

        if(c=='\177') printf("\nBackspace received - Exiting\n\n");
        else printf("\nNon-backspace received - Exiting\n\n");
}