How to Wait for a Key Press in C

I wrote this for QNX, but as far as I am aware, it uses standard Unix functions, so I suspect (hope), this is a fairly portable technique. But please check for compilability and reliability. I'd be interested to hear from anyone who can comment on its portability.

Minimal demo of how to preform a KeyPressed or Readkey (a la Borland Pascal) feature in C. The select function waits until either an error occurs, or the specified time elapses, or a key is pressed.

The fds is a file descriptor set -- the select function checks if the specified files are ready for reading or writing. The file descriptor in this case is specified to be stdin for the keyboard. The first NULL argument is checked for writing, but we are only interested in reading (input) files, so we can pass in a null. The first argument of all is the number of file descriptors in the set to actually check, and we only want to check the first one.

#include <stdio.h>
#include <fcntl.h> /* For STDIN_FILENO */
#include <sys/select.h> /* For select() */

main( void )
   int select_result;
   fd_set read_fds;
   struct timeval timeout;
   FD_ZERO( &read_fds );
   FD_SET( STDIN_FILENO, &read_fds );
   timeout.tv_sec = 2;
   timeout.tv_usec = 0;
   select_result = select( 1, &read_fds, NULL, NULL, &timeout );

   switch (select_result) {
      case -1:
      printf( "Error\n" );
      case 0:
      printf( "Timeout\n" );
      /* Select returns a one if a key is pressed */
      printf( "Number = %d\n", select_result );


Home About Me
Copyright © Neil Carter

Content last updated: 2003-11-18