Linux does not have an equivalent to the conio.h getch() and kbhit() which respectively return a single character from the keyboard and return true if a key is waiting; to get this functionality it seems you have to play around with the termio structures... it expects to hand off a string when the return key is pressed, which is less than handy in some circumstances.
I'm using code based on this, but this displays my problem: the basic idea is
- if there's a key waiting
- grab it
- output it to the console
but the issue is that the output is delayed until the next key is pressed. Anyone know a way to stop this? It looks as if the putchar is being called when expected, but nothing on the console until the next key is ready - which is less than handy to type with. Any thoughts cheerfully accepted, thanks!
#include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> void changemode(int); int kbhit(void); int main(void) { int ch; while (1) { changemode(1); while ( !kbhit() ) { //putchar('.'); } ch = getchar(); //printf("\nGot %c\n", ch); putchar (ch); changemode(0); } return 0; } void changemode(int dir) { static struct termios oldt, newt; if ( dir == 1 ) { tcgetattr( STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt); } else { tcsetattr( STDIN_FILENO, TCSANOW, &oldt); } } int kbhit (void) { struct timeval tv; fd_set rdfs; tv.tv_sec = 0; tv.tv_usec = 0; FD_ZERO(&rdfs); FD_SET (STDIN_FILENO, &rdfs); select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv); return FD_ISSET(STDIN_FILENO, &rdfs); }
Neil