Search code examples
cgetchar

Using getchar to immediately retrieve keystrokes


I'm trying to use getchar() to retrieve 1 keystroke at a time from the keyboard. Though it does this, the problem I'm having is doesn't send it immediately, it waits for the enter key to be pressed and then it reads 1 char at a time from the buffer.

int main(){
    char c = getchar();
    putchar(c);

return 0;
}

How do I immediately read each keystroke as it's pressed from the keyboard? Thanks


Solution

  • You have to pass in raw mode. I paste you code from:

    http://c.developpez.com/faq/?page=clavier_ecran

    #include <termios.h>
    #include <unistd.h>
    
    void mode_raw(int activer)
    {
    static struct termios cooked;
    static int raw_actif = 0;
    
    if (raw_actif == activer)
        return;
    
    if (activer)
    {
        struct termios raw;
    
        tcgetattr(STDIN_FILENO, &cooked);
    
        raw = cooked;
        cfmakeraw(&raw);
        tcsetattr(STDIN_FILENO, TCSANOW, &raw);
    }
    else
        tcsetattr(STDIN_FILENO, TCSANOW, &cooked);
    
    raw_actif = activer;
    

    }

    After that, you don't need to tap Enter key.

    EDIT: Like Emmet says, it's the Unix version, it's depend of the environment.