I was trying to do the exercise 1.10 of K&R so this is :
/*
* Exercise 1.10
*
* Write a program to copy its input to its output, replacing each tab
* by \t, each backspace by \b, and each backslash by \\. This makes tab
* and backspaces visible in an unambiguous way.
*
*/
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
if (c == '\t')
printf("\\t");
else if (c == '\b')
printf("\\b");
else if (c == '\\')
printf("\\\\");
else
printf("%c", c);
}
}
If I compile this code with gcc -std=c99 1.10.c -o test
it doesn't print \b
if i use Backspace. Why? And how I could try to get \b
pressing Backspace in Linux ?
A guy has said me:
Your program probably doesn't see that backspace. Terminals buffer by line, by default. So does stdin. Well, stdin's buffering is IDB.
Usually, the console interprets special characters, like backspace or Ctrl-d. You can instruct the console to not do this with stty
.
Before you run the program, you can set the tty to ignore backspace mode with
stty erase ''
and restore the console afterwards with
stty sane
This passes the backspace characters Ctrl-h unchanged to the program you're running.
If this doesn't show any difference, then the backspace key may be mapped to DEL instead of Ctrl-h.
In this case you can just start your program and type Ctrl-h everywhere you would have used the backspace key. If you want to catch the backspace key nevertheless, you must also check for DEL
, which is ASCII 127
/* ... */
else if (c == '\b' || c == 127)
printf("\\b");