Jeegar Patel Jeegar Patel -4 years ago 258
C Question

What is Equivalent to getch() & getche() in Linux?

I am not able to find equivalent header file for conio.h in Linux.

Is there any option for

function 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.

Answer Source
#include <termios.h>
#include <stdio.h>

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;

Just copy these functions and use it. I have found this snippet on google long before and I have saved it, Finally I've opened it after a long time for you!Hope it helps! Thanks

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download