title: Using system calls in C to read keyboard events
body: <p>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. </p>
  
  <p>I'm kind of at a loss as to the simplest way to do this. </p>
  
  <p>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. </p>
  
  <p>Where i'm getting stuck is the fact that these are system calls, and i'm basically unsure how to handle them.</p>
  
  <p>The code below definitely won't compile, just putting it there as a rough demonstration of what i am trying to do. </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;fcntl.h&gt;
  
  int main(void)
  {
      // errors on opening
      int fd = open("/dev/input/event4", O_RDONLY);
      if(fd &lt; 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;
  }
  </code></pre>