Pages

Saturday, March 24, 2012

getch(), getche() & clrscr() in gcc

Sometimes, we need to use "conio.h" in Linux (gcc). Functions like getch(), getche() and clrscr() are present in the header file "conio.h". getch() prompts the user to press a character and that character is not printed on screen. getche() prompts the user to press a character and that character is printed on screen. clrscr() clears the console screen.
Given below is the code you need to save under the name conio.h to make the functions work.
       
#include <termios.h>
#include <unistd.h>
#include <stdio.h>

/* reads from keypress, doesn't echo */
int getch(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

/* reads from keypress, echoes */
int getche(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

/* Clears screen */
void clrscr(void)
{
 system("clear");
}       
 

Just include the above header files and you can use the these functions.

#Source: Internet

No comments:

Post a Comment