4

I wrote the following code as part of an exercise in chapter one of K&R. The code replaces tabs and backslashes as expected, but it does not replace backspaces with \b. Here is the code:

#include <stdio.h>


int main(void)
{
    int c;

    while((c = getchar()) != EOF)
    {
        if (c == '\t')
        {
            putchar('\\');
            putchar('t');
        }

        if (c == '\b')
        {
            //putchar('\\');
            //putchar('b');
            printf("\\b");
        }

        if (c == '\\')
        {
            putchar('\\');
            putchar('\\');
        }

        if (c != '\t' && c != '\b' && c != '\\')
        {
            putchar(c);
        }
    }


    return 0;
}

I've looked through Stack Overflow. The answers to this question talk about the shell's consuming the backspace, the result being that code I write never sees the backspace. This brings me to my question: what happens to the input I provide at the keyboard? I assume this becomes part of the stdin stream. Clearly, though, not all the characters I enter make it to my code. Can someone please explain what processing happens between my keystrokes and the handling of that input by my code? Also, is there a way for my code to read the stdin buffer before this processing occurs?

I hope these questions make sense. It took me a while to figure out what I am trying to ask, and I'm not sure I've figured that out completely.

BruceM
  • 319
  • 1
  • 3
  • 8

2 Answers2

3

When getchar() is reading from an interactive console, the function won't return until after you press the ENTER key. Then it will return with the first character entered, and immediately return for each subsequent character you entered up to a newline character.

If you pressed backspace, delete, or an arrow key prior to pressing ENTER, the terminal processes those keystrokes and will only send the "final result" when you press ENTER.

Had you been reading from a redirected-in file (i.e. you called you program as ./myprog < input_file) or piped output from another program (i.e. ./otherprog | ./myprog), then getchar would return right away for each character and you would see everything, including control characters and individual UTF-8 bytes.

dbush
  • 205,898
  • 23
  • 218
  • 273
1

That's because the backspace character never gets to getchar in standard input. When you type backspace, it just cancels the character you just typed.

If you manage to create a text file with backspace characters and feed it to your program that will work, though.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219