faqts : Computers : Programming : Languages : C

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

13 of 84 people (15%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

Please translate this PASCAL line to UNIX C: if (keypressed) then ch:=readkey();

Nov 12th, 2003 08:02
Kenan Bektas, Milan Farhs,


First, create a function(kbhit), then call it in the main or other 
procedures. The kbhit code is not mine. I apologize from the author, 
cannot find her/his name now.
#include <sys/timeb.h>
#include <termios.h>
int kbhit(void)
{
    struct termios term, oterm;
    int fd = 0, c = 0;
    tcgetattr(fd, &oterm);
    memcpy(&term, &oterm, sizeof(term));
    term.c_lflag = term.c_lflag & (!ICANON);
    term.c_cc[VMIN] = 0;
    term.c_cc[VTIME] = 1;
    tcsetattr(fd, TCSANOW, &term);
    c=getchar();
    tcsetattr(fd, TCSANOW, &oterm);
    if (c != -1) ungetc(c, stdin);
return ((c!=-1)?1:0);
}
..
And somewhere in your program/procedure(s) do a call;
int ch;
..
if(kbhit) ch=getch();
switch (ch) {
        case 'A': <do something>; 
                  break;
}//switch