Search code examples
ccommand-line-interface

How to handle key presses in C


I'd like to create a CLI program in C/C++ with the following capability: when user presses a combination of keys, I want to be able to perform some kind of action without waiting for "enter" to be pressed. Just like ctrl+r in bash enters reverse search mode. If possible I'd like to stick to standard libraries as much as possible and if I must be platform dependent, I'd like to go POSIX way (I'm working with Linux or macOS).


Solution

  • The bash terminal uses the curses library you can also use it in your cli programs.

    You can use the getch() function to get a character from the keyboard.

    If you set no delay mode then it does not wait for a newline and should immediately return a character.

    And if you enable no echo then it also won't print the character to the screen.

    An answer to this question also provides a neat little example of the getch() function.