Nov
6

Equivalent to getch() & getche() in Linux

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.

 

#include 
#include 
 
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;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  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.

 

JIGAR PATEL

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 JigAr Patel

More PostsWebsiteTwitterFacebook

You may like to read this also....

Post comment

*

Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

36 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link