Created
May 30, 2010 18:08
-
-
Save pcyu16/419205 to your computer and use it in GitHub Desktop.
getch for unix-like system
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <termios.h> | |
| #include <unistd.h> | |
| #include <fcntl.h> | |
| int kbhit(void) | |
| { | |
| struct termios oldt, newt; | |
| int ch; | |
| int oldf; | |
| tcgetattr(STDIN_FILENO, &oldt); | |
| newt = oldt; | |
| newt.c_lflag &= ~(ICANON | ECHO); | |
| tcsetattr(STDIN_FILENO, TCSANOW, &newt); | |
| oldf = fcntl(STDIN_FILENO, F_GETFL, 0); | |
| fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK); | |
| ch = getchar(); | |
| tcsetattr(STDIN_FILENO, TCSANOW, &oldt); | |
| fcntl(STDIN_FILENO, F_SETFL, oldf); | |
| if(ch != EOF){ | |
| ungetc(ch, stdin); | |
| return 1; | |
| } | |
| return 0; | |
| } | |
| int getch() | |
| { | |
| while(!kbhit()); | |
| return getchar(); | |
| } | |
| int main(void) | |
| { | |
| while(1) | |
| printf("get \"%c\"\n", getch()); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment