When I read the C Programming Language and do the exercise 1-10, there is a problem made me puzzled.
It's said that when I enter a backspace, the character is processed by the console driver and not delivered to the program, so what I can do is create a file with embedded backspace.However, it's seemed useless no matter I directly enter '\b' or press Ctrl + H.
When I press Ctrl + H, the screen will show "\b", but when I run the program, it seems that the program will still see it as two characters '\' and 'b'. No matter what I enter, it never shows "\backspace" when I run the program.
What should I do to make the program recognize it as a character of backspace?
My codes are like following:
#include <stdio.h>
int main()
{
int c;
while((c=getchar())!=EOF){
if(c=='\t')
printf("\\t");
else if(c=='\\')
printf("\\\\");
else if(c=='\b')
printf("\\backspace");
else
putchar(c);
}
}
I don't think the problem is with your code, but with the way you wrote the backspace character in your text editor.
You have to use a special key combination in vim to enter control characters such as backspace. In your case, you should type ctrl + v followed by ctrl + h. That should produce a real backspace character.
To see whether you have produced an actual backspace character, you can use hexdump
:
$ hexdump myfile
00000000 68 65 6c 6c 6f 20 08 77 6f 72 6c 64 |hello .world|
^^
Notice the 08
, which is the backspace character (in C, it's denoted \b
).
Another way to produce the backspace character is to simply write it via a program in C:
#include <stdio.h>
int main(void) {
FILE *f = fopen("myfile", "w");
fputs("hello \bworld", f);
fclose(f);
return 0;
}
The problem is not really in your program, but, like you said, in your terminal driver. The odd behaviour, as observed by your program, is a consequence of the Unix terminal model.
Notice that after you press Tab, you probably also have to press Enter before your program sees the Tab as a \t
character. That means that your terminal is in "cooked" mode (i.e., not raw mode). Similarly, the terminal driver will handle Ctrl + H before your program's getchar()
will ever get a chance to see it.
What you can do is run stty -icanon
before launching your program. (Alternatively, you can do it programmatically within your program's initialization routine.) Then, keystrokes such as Tab and Ctrl + H keypress will be instantly picked up by getchar()
, literally.
To restore the default terminal behaviour, use stty icanon
or stty sane
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With