Skip to content

Instantly share code, notes, and snippets.

@vsajip
Created February 19, 2012 17:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save vsajip/1864660 to your computer and use it in GitHub Desktop.
Save vsajip/1864660 to your computer and use it in GitHub Desktop.
Keyboard hit testing
#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 main()
{
printf("Press any key:");
fflush(stdout);
while (!kbhit())
;
puts("Done.");
return 0;
}
@darealshinji
Copy link

Can you specify a license for this? Preferably something permissive like zlib, MIT or even UnLicense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment