Pengecekan Keyboard Stroke di C UNIX

Posted: November 6, 2008 in C/C++, Programming
Tags: , ,

Kadangkala kita perlu melakukan pengecekan apakah ada penekanan tombol di keboard apa enggak, kalau keboard lagi gak ditekan, eksekusi perintah A, kalau keyboard sedang gak ditekan, eksekusi perintah B. Nah, gimana seh caranya? kebetulan saya habis diajari teman saya :

int kbhit()
{
    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=EOF;
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    fcntl(STDIN_FILENO, F_SETFL, oldf);
    if(ch != EOF)
    {
        ch=EOF;
        ungetc(ch, stdin);
        return 1;
    }

    return 0;
}

Jangan lupa kalau potongan program diatas pake header termios.h

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s