Search code examples
clinuxgetchar

Getting capital O from getchar when pressing home or end


I'm using this in my C code:

system("stty -echo -icanon");

This is part of a homework assignment, but this particular part is something I'm working on beyond the requirements of the assignment.

We're implementing a shell, and we've been given a bunch of code to start with. The code doesn't use ncurses (which I'd use if I could) and changing that would require rewriting a lot of the provided code.

When I press my HOME or END key, I get a capital O (that's an o as in Open) and then the HOME and END key. I'm using getchar() to get the character.

It seems that these are the only two keys that do it, but I'm not sure. I'm not 100% if the provided system function call is the only thing that is different (we also set stdout to non-blocking, but that shouldn't matter).

I'm really confused, and I'd like to implement the END and HOME keys because I use them a lot.

I'm sorry if this isn't a lot of information. I don't know enough about system to really understand what the ramifications of -echo and -icanon are for stty. I've looked at the man page, but I still can't figure it out.

EDIT

From Alex Brown's answer, I confirmed that I am getting escaped characters. I have something like the following (in bad pseudo code):

while (TRUE) 
    ch = getchar()
    switch (ch)
        case HOME:
        case END:
            don't print anything...
            break

        default:
            printf(ch);
            break

So it's printing out the O from the escape sequence, but not the [ (I have 0x48 for HOME and 0x46 for END). Still stumped on how to get the real keycode...


Solution

  • For a console application, the keys such as Home and End are usually transmitted as an escape sequence. The exact sequence depends on the terminal program you are using and how it is configured. The information is traditionally stored in termcap/terminfo, and ncurses looks it up from there based on your terminal type.

    Gnome Terminal sends:

    • ESC O H (0x1b 0x4f 0x48) for Home and
    • ESC O F (0x1b 0x4f 0x46) for End.

    KDE Konsole and xterm send:

    • ESC [ H (0x1b 0x5b 0x48) for Home and
    • ESC [ F (0x1b 0x5b 0x46) for End.

    If you read an ESC character followed by [ or O, you will need to read an additional character in order to determine which key was pressed.