#include #include #include #include // For Getch #include // for Getch #include // For KBHIT #include // For KBHIT unsigned getch(void) { fd_set kb; char ch = '\0'; termios newtty,oldtty; tcgetattr(0, &oldtty); //Get current TTY attributes newtty = oldtty; // Start out with the same TTY attributes. newtty.c_lflag &= ~ICANON; // Turn of the wait for end of line (EOL). newtty.c_lflag &= ~ECHO; // Don't echo any characters to the display. newtty.c_cc[VMIN] = 1; // Set the minimum character buffer. newtty.c_cc[VTIME] = 0; // Set the minimum wait time. tcsetattr(0, TCSAFLUSH, &newtty); // Set our new tty attributes. FD_ZERO(&kb); // Clear out the file descriptor set. FD_SET(0, &kb); // Add STDIN (fd 0) to the file descriptor set. select(1, &kb, NULL, NULL, NULL); // Wait for a character from STDIN. read(1, &ch, 1); // Read one byte from STDIN. tcsetattr(0, TCSAFLUSH, &oldtty); // Restore the original TTY settings. return ch; // Return the character we read. } int kbhit(void) { struct timeval tv; fd_set read_fd; /* Do not wait at all, not even a microsecond */ tv.tv_sec=0; tv.tv_usec=0; /* Must be done first to initialize read_fd */ FD_ZERO(&read_fd); /* Makes select() ask if input is ready: * 0 is the file descriptor for stdin */ FD_SET(0,&read_fd); /* The first parameter is the number of the * largest file descriptor to check + 1. */ if(select(1, &read_fd, NULL, NULL, &tv) == -1) return 0; /* An error occured */ /* read_fd now holds a bit map of files that are * readable. We test the entry for the standard * input (file 0). */ if(FD_ISSET(0,&read_fd)) /* Character pending on stdin */ return 1; /* no characters were pending */ return 0; }