1

Using getchar() to read stdin, when I press any arrow key of my keyboard, I get weird symbols (like this: ^[[A).

#include <stdio.h>

int main(void) {
    getchar();
}

How I can avoid this and make the arrow keys work like bash does?

Thanks for reading :).

1 Answers1

1

You can't really have the arrow keys working like that with getchar(). The shells have their own line-editing features. Normally when a program is executed, the shell will first set the terminal to so-called cooked/canonical mode.

In canonical mode all input is line-buffered and you can edit the line in limited manner, deleting with backspace and so. All other characters will be echoed back as-is. Thus the arrow keys will often send multiple bytes, such as ESC [ A which will be displayed as ^[[A if echoing is on.

Now what bash and other advanced shells do is they turn off the canonical mode, so that they can receive the keys as soon as they are pressed. They also disable the echoing so that the typed characters are not displayed automatically. But that makes bash itself responsible for things like updating cursor position or updating the displayed characters. The arrow keys still produce the same byte sequences. You can actually try this by typing rapidly the same sequence in bash: ESC,[,shift+A and bash thinks you pressed the Up arrow key.

You can either write your own routines for doing the line editing, or you can use a ready-made library such as libreadline or libeditline for simple line editing, or use the curses/ncurses to write complex interfaces such as text editors or menu-based GUIs.