简体   繁体   中英

Using system calls in C to read keyboard events

Just trying to seek to understand. I'm writing a small program that will read in a keystroke event from the keyboard, and trigger certain events (using a switch statement). I'm making some assumptions, and attempting to treat the keyboard like a txt file to read from.

I'm kind of at a loss as to the simplest way to do this.

What i WANT to do it open the file(keyboard event4), and use something like fgets to read it in character by character in an infinite while loop, then use a switch statement to break out of the loop and exit.

Where i'm getting stuck is the fact that these are system calls, and i'm basically unsure how to handle them.

The code below definitely won't compile, just putting it there as a rough demonstration of what i am trying to do.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(void)
{
    // errors on opening
    int fd = open("/dev/input/event4", O_RDONLY);
    if(fd < 0)
    {
        printf("error while opening/n");
        return 1;
    }

    int keystroke = 0;

    while (1)
    {
       keystroke = fgetsc(fd);

       switch(keystroke)
       {
           case '1' :
              break;
           case '2' :
              break;
           case '3' : 
              break;
           default:
              printf("waiting for 1, 2, 3/n");
          }

    close(fd);
    return 0;
}

1) Read "raw keyboard input" is generally OS-dependent. The APIs and techniques can vary greatly depending if you're on Windows vs Linux, for example.

2) It sounds like you're on a *nix variant (Linux or MacOS, for example). If you want to do all the "grunge" yourself, here's a great "howto":

3) You'll need to put the keyboard device into "raw", "unbuffered" mode in order to read keystrokes. Among other things...

4) I would encourage you, however, to leverage a higher-level library, like ncurses or SDL .

'Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM