Erase a character when stty is set to raw mode in C

Viewed 856

I was trying to get a paragraph of text including the newlines without the user needing to press enter everytime the getch untill the user presses CTRL+C at which point loop shown below will exit out . But the problem using this approach in that , once the terminal is set into raw mode , it also shows those ^M when i press Enter and shows the ^? when I press backspace. How to fix this ? I have also tried giving system("/bin/stty raw -echo isig");But this method also didnt work( no charecters show as i type)

int main(void)
{
    char str[1000] ,c , i=0 ;

    system("/bin/stty raw") ;
    while(1)
    {
        c = getchar();
        str[i++] = c ;
        if(c==3)break;
        if(c==13)puts("\r");
    }

    system("/bin/stty cooked") ;

    for(i=0 ;str[i] ; i++) printf("%c",str[i]) ;
}

Also the string produced at the end (str) is also not having the right characters. In fact when i print it , it only prints the last line.

1 Answers

You can try printf("\b \b"); to erase a character, but first you have to check whether or not the backspace was pressed, you will need to find out the code for backspace in your particular machine :

if (ch == 0x7F)         // the code for backspace on my machine
    printf("\b \b");    // simulate erasing a character using two '\b' and a space ' '

alternatively you can use VT100 escape codes:

if (ch == 0x7F)         // the code for backspace on my machine
    printf("\b\33[K");  // clear line from cursor right
Related