C-Menu 0.2.9
A User Interface Toolkit
Loading...
Searching...
No Matches
enterchr.c
Go to the documentation of this file.
1/** @file enterchr.c
2 @brief Enter a single character from keyboard
3 @author Bill Waller
4 Copyright (c) 2025
5 MIT License
6 billxwaller@gmail.com
7 @date 2026-02-09
8 */
9
10#include <cm.h>
11#include <fcntl.h>
12#include <stdbool.h>
13#include <string.h>
14#include <sys/ioctl.h>
15#include <termios.h>
16#include <unistd.h>
17
18/** @example
19 @code
20 key=$(enterchr "Are you sure?: ")
21 if [ "$key" = "Y" ]; then
22 echo "You entered Y"
23 else
24 echo "You entered N"
25 fi
26 @endcode
27 */
28
29/** @brief Capture the current terminal settings for later restoration.
30 @note can be used in scripts to get a single character response from a
31 user. For example: response=$(./enterchr "Enter Y or N: ") if [ "$response"
32 = "Y" ]; then echo "You entered Yes" else echo "You entered No" fi
33 @note This function saves the current terminal settings into a global
34 variable so that they can be restored later. It should be called before
35 modifying the terminal settings to ensure that the original settings can be
36 restored when the program exits or is interrupted.
37 */
38int main(int argc, char **argv) {
39 char c = 'Y';
40 char *msg;
41 struct termios raw_tioctl;
42 char errmsg[128];
43
44 if (argc < 2)
45 strcpy(errmsg, "Press any key");
46 else
47 strcpy(errmsg, argv[1]);
49 raw_tioctl = shell_tioctl;
50 mk_raw_tioctl(&raw_tioctl);
51 tcflush(0, TCOFLUSH);
52 while (1) {
53 msg = errmsg;
54 while (*msg) {
55 write(2, msg++, 1);
56 }
57 if (read(0, &c, 1) > 0) {
58 write(1, &c, 1);
59 break;
60 }
61 }
63 if (c == (char)0x1b)
64 return (1);
65 return (0);
66}
int main(int argc, char **argv)
Capture the current terminal settings for later restoration.
Definition enterchr.c:38
struct termios shell_tioctl
Definition scriou.c:22
bool capture_shell_tioctl()
capture_shell_tioctl() - capture shell terminal settings
Definition scriou.c:43
bool mk_raw_tioctl(struct termios *)
mk_raw_tioctl() - set terminal to raw mode
Definition scriou.c:126
bool restore_shell_tioctl()
restore_shell_tioctl() - restore shell terminal settings
Definition scriou.c:56