Equivalent to getch() & getche() in Linux

By -

Once in one situation i need to use getch() and getche() function in Linux based application so i have searched a lot for Equivalent header file for conio.h in Linux,But i came to know there is not any header file/library equivalent to conio.h in linux.

I want to make a switch case base menu where the user will give his option just by pressing one key & process should be moved ahead. I don’t want to let user to press ENTER after pressing his choice.

Somebody has suggest me very magical code for getch() and getche() function for linux which is i am sharing here.


static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo) 
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  new = old; /* make new settings same as old settings */
  new.c_lflag &= ~ICANON; /* disable buffered i/o */
  new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
  tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
/* Restore old terminal i/o settings */
void resetTermios(void) 
  tcsetattr(0, TCSANOW, &old);
/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
  char ch;
  ch = getchar();
  return ch;
/* Read 1 character without echo */
char getch(void) 
  return getch_(0);
/* Read 1 character with echo */
char getche(void) 
  return getch_(1);
/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;

you can change getch() and getch() function more precious as much
your requirement but this base code will help you lot.

hey I am an Artist who love to write code...! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here Jeegar Patel

Leave a Reply

Your email address will not be published. Required fields are marked *