Skip to content
Advertisement

How to get the last key pressed without stopping the C program?

Writing an application with command line interface and I would like to know at any time if F1 or ESC or an arrow key is pressed. What is the simplest way of doing this? I would like to avoid using a readline type library.

This is a Linux specific question; the program is not multithreaded.

Advertisement

Answer

An implementation of kbhit() for Linux is presented in Beginning Linux Programming page 167. You can read it on-line at the link provided.

EDIT: I mention kbhit() because it was posted as a solution before it was made clear that the question related to Linux. Unfortunately the solution has been deleted, which is unfortunate. The principle is that when kbhit() returns non-zero, a subsequent blocking character-oriented read call will not block. This is only true for character oriented input; getchar() and other standard functions that read stdio are typically line-oriented, so block until newline.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement