Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

K&R 1-10, the terminal eats the backspace

Tags:

c

K&R C 1-10 reads:

"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 tabs and backspace visible in an unambiguous way."

I have the following code and it does not work with the backspace character because the terminal eats the character. It doesn't seem like there's a solution with the material covered in the book so far. What would the solution be?

#include <stdio.h>

main()
{
    int c;

    while((c = getchar()) != EOF) {

        switch (c) {
            case '\t':
                printf("\\t");
                break;
            case '\b':
                printf("\\b");
                break;
            case '\\':
                printf("\\\\");
                break;
            default:
                putchar(c);
        }
    }
}
like image 951
Steve M Avatar asked Jan 08 '13 01:01

Steve M


2 Answers

This is because the Operating System is handling terminal IO, and processes the characters from the keyboard before your program gets to see them.

If you are on a Unix/Linux system, you could wrap the execution of your program like this:

$ stty -icanon -echo; ./a.out; stty icanon echo

This will disable the terminal driver from processing the input in some specific ways: icanon enables the handling of of things like backspace processing, while echo causes the characters you type to be printed. Since your program echos the characters itself, you can turn echo off. The only problem with this is that -icanon also stops EOF processing, so you will need to add an extra condition to get out of the loop:

#include <stdio.h>

#define CTRL(x) (x & 0x1f)

main()
{
    int c;

    while((c = getchar()) != EOF && c != CTRL('d')) {
...

It is also a good idea while testing programs like this to run them in a separate window, so you can kill the entire session quickly and easily if you end up in a strange terminal mode!

like image 147
NickStoughton Avatar answered Sep 17 '22 23:09

NickStoughton


Nothing wrong here. If you were to run this program on a file that contained the backspace character, it would properly convert it. For terminal input, the program will not receive the backspace as it is managed by the input routines.

like image 26
DrC Avatar answered Sep 19 '22 23:09

DrC