11/06/2011

Emulate getch() in Linux

Now, suppose you need to use getch() function in Linux. Since this is not a standard function, and is constructed for DOS, it's not really defined for Linux. However, you can simply emulate it... Here's how

Since I'm a noob, I didn't know that there is not real replacement for getch() in Linux. Here's what I found after some proper googling (I googled badly first, so I had to change the query):
#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int getch() {
  struct termios oldt, newt;
  int            ch;
  tcgetattr( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
  return ch;
}
(source)

Now when you know it, you can do stuff like Hacker Typer :)

No comments:

Post a Comment

If you have anything useful to say (ideas, suggestions, questions, business proposals, or just "Thank you!"), please feel free to comment! Also, you can use my e-mail and/or find me on Twitter!