Skip to content

Instantly share code, notes, and snippets.

@TheLastBilly
Last active November 5, 2021 18:53
Show Gist options
  • Save TheLastBilly/c57db3663bbc419518b51612841cdce8 to your computer and use it in GitHub Desktop.
Save TheLastBilly/c57db3663bbc419518b51612841cdce8 to your computer and use it in GitHub Desktop.
// clicker.c
// Count the times each key has been pressed
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
// Yeah, I'm lazy, get over it
#define roe(_expr) if((ret = (_expr)) < 0) return ret
// Make sure we read stdin one key at the time
// https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed
static int
getch()
{
int ret = 0;
char buf = 0;
struct termios t = {0};
roe(tcgetattr(0, &t));
t.c_lflag &= ~ICANON;
t.c_lflag &= ~ECHO;
t.c_cc[VMIN] = 1;
t.c_cc[VTIME] = 0;
roe(tcsetattr(0, TCSANOW, &t));
roe(read(0, &buf, 1));
t.c_lflag |= ICANON;
t.c_lflag |= ECHO;
roe(tcsetattr(0, TCSADRAIN, &t));
return buf;
}
int
main()
{
int ret = 0;
unsigned long int counters[128] = {0};
while(1)
{
roe(getch());
switch(ret)
{
// If I pressed ESC...
case 27:
return 0;
// Everything else
default:
printf("%c: %ld\n", ret, ++counters[ret > 127 ? 127 : ret]);
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment