Re: kbhit() MSDOS equivalent in Linux
Mario Olimpio de Menezes wrote:
>
> Hi,
>
> I received a message from two students about the kbhit() C MSDOS
> function equivalent in Linux. I'm not a good C programmer and could not
> help them. If somebody can, please.
> Thanks, and sorry for the little off-topic Debian.
Here ya go,
A little hefty, but it does the job.
-- start of code snippet
#include <stdio.h>
#include <termios.h>
static struct termios orig, new;
static int peek = -1;
int main()
{
int ch =0;
tcgetattr(0, &orig);
new = orig;
new.c_lflag &= ~ICANON;
new.c_lflag &= ~ECHO;
new.c_lflag &= ~ISIG;
new.c_cc[VMIN] = 1;
new.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new);
while(ch != 'q') {
printf("looping\n");
sleep(1);
if(kbhit()) {
ch = readch();
printf("you hit %c\n",ch);
}
}
tcsetattr(0,TCSANOW, &orig);
exit(0);
}
int kbhit()
{
char ch;
int nread;
if(peek != -1) return 1;
new.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new);
nread = read(0,&ch,1);
new.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new);
if(nread == 1) {
peek = ch;
return 1;
}
return 0;
}
int readch()
{
char ch;
if(peek != -1) {
ch = peek;
peek = -1;
return ch;
}
read(0,&ch,1);
return ch;
}
-- end of code snippet
Hope this helps!
- mike
--
To UNSUBSCRIBE, email to debian-user-request@lists.debian.org
with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
Reply to: