Tuesday, September 11, 2012

Implementation of getch() and getche() in Linux

#include <stdio.h>
#include <termios.h>
   
    int getch()
    {
        struct termios initialrsettings, newrsettings;
        char ch[2];
        tcgetattr(fileno(stdin), &initialrsettings);
        newrsettings = initialrsettings;
        newrsettings.c_lflag &= ~ECHO;
        newrsettings.c_lflag &= ~ICANON;
        if(tcsetattr(fileno(stdin), TCSAFLUSH, &newrsettings) != 0)
            fprintf(stderr,"Could not set attributes\n");
        else
        {
        fgets(ch,2,stdin);
        tcsetattr(fileno(stdin), TCSANOW, &initialrsettings);
        return ch[0];
        }
    }
   
    int getche()
    {
        struct termios initialrsettings, newrsettings;
        char ch[2];
    
        tcgetattr(fileno(stdin), &initialrsettings);
        newrsettings = initialrsettings;
        newrsettings.c_lflag &= ~ICANON;
        if(tcsetattr(fileno(stdin), TCSAFLUSH, &newrsettings) != 0)
            fprintf(stderr,"Could not set attributes\n");
        else
        {
        fgets(ch,2,stdin);
        tcsetattr(fileno(stdin), TCSANOW, &initialrsettings);
        return ch[0];
        }
    }

No comments:

Post a Comment