How to implement getch() function of C in Linux?

Viewed 69329

In TurboC++, I can use the getch() function from conio.h. But in Linux, gcc doesn't provide conio.h. How can I get the functionality of getch()?

12 Answers

If, for any reasons, you can't use curses, try this:

# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
# include <termios.h>

/* get a single char from stdin    */
int getch(void)
{
   struct termios oldattr, newattr;
   int ch;
   tcgetattr(0, &oldattr);
   newattr=oldattr;
   newattr.c_lflag &= ~( ICANON | ECHO );
   tcsetattr( 0, TCSANOW, &newattr);
   ch=getchar();
   tcsetattr(0, TCSANOW, &oldattr);
   return(ch);
}

conio.h is only in Dos,

for linux, use

sudo apt-get install libncurses-dev

& then

-lncurses

// In IDE, you have to link it: for example: codeblocks, Setting -> Compiler -> Linker setting, and add 'ncurses'

You can also use system command to control the terminal in linux like this

char getch()    {

        char c;

        system("stty raw -echo");

        c = getchar();

        system("stty -raw echo");

        return c;

}

This function does not requires the user to press enter and takes input from the user without echoing It requires you to add stdlib.h library to your code

Note : This function is only applicable to UNIX-based OS

Any improvements or pointing out any issues in the code will be appreciated

Regards

If you want to use conio.h on Ubuntu, then follow these steps:-

  1. Open terminal
  2. sudo apt-get install git
  3. git clone https://github.com/zoelabbb/conio.h.git
  4. cd conio.h
  5. sudo mv conio.h /usr/include/
  6. Close your IDE and open again. Done.

If you are in trouble then follow this link: enter link description here

Related