Skip to content

Instantly share code, notes, and snippets.

@m1lkweed
Last active May 26, 2023 19:36
Show Gist options
  • Save m1lkweed/e40d3144007a3c0472cd789be942e6f7 to your computer and use it in GitHub Desktop.
Save m1lkweed/e40d3144007a3c0472cd789be942e6f7 to your computer and use it in GitHub Desktop.
Windows' kbhit() ported to POSIX systems
#include <unistd.h> // STDIN_FILENO
#include <termios.h> //tcsetattr/tcgetattr
#include <sys/ioctl.h> // ioctl
int kbhit(){
struct termios term;
tcgetattr(STDIN_FILENO, &term);
struct termios term2 = term;
term2.c_lflag &= ~ICANON; // disable canonical mode
tcsetattr(STDIN_FILENO, TCSANOW, &term2);
int byteswaiting;
ioctl(STDIN_FILENO, FIONREAD, &byteswaiting);
tcsetattr(STDIN_FILENO, TCSANOW, &term); // restore original terminal settings
return byteswaiting /* > 0 */;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment