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#ifdef __USE_GNU_GETTEXT
19#include <libintl.h>
20#define _(String) gettext(String)
21#define gettext_noop(String) String
22#define N_(String) gettext_noop(String)
23#else
24#define _(String) (String)
25#define N_(String) String
26#define textdomain(Domain)
27#define bindtextdomain(Package, Directory)
28#endif
29
30/** @example
31 @code
32 key=$(enterchr "Are you sure?: ")
33 if [ "$key" = "Y" ]; then
34 echo "You entered Y"
35 else
36 echo "You entered N"
37 fi
38 @endcode
39 */
40
41/** @brief Capture the current terminal settings for later restoration.
42 @details can be used in scripts to get a single character response from a
43 user. For example: response=$(./enterchr "Enter Y or N: ") if [ "$response"
44 = "Y" ]; then echo "You entered Yes" else echo "You entered No" fi
45 This function saves the current terminal settings into a global
46 variable so that they can be restored later. It should be called before
47 modifying the terminal settings to ensure that the original settings can be
48 restored when the program exits or is interrupted.
49 */
50int main(int argc, char **argv) {
51 char c = 'Y';
52 char *msg;
53 struct termios raw_tioctl;
54 char emsg[128];
55
56 if (argc < 2)
57 strcpy(emsg, _("Press any key"));
58 else
59 strcpy(emsg, argv[1]);
61 raw_tioctl = shell_tioctl;
62 mk_raw_tioctl(&raw_tioctl);
63 tcflush(0, TCOFLUSH);
64 while (1) {
65 msg = emsg;
66 while (*msg) {
67 write(2, msg++, 1);
68 }
69 if (read(0, &c, 1) > 0) {
70 write(1, &c, 1);
71 break;
72 }
73 }
75 if (c == (char)0x1b)
76 return (1);
77 return (0);
78}
#define _(String)
Definition amort.c:23
int main(int argc, char **argv)
Capture the current terminal settings for later restoration.
Definition amort.c:41
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:132
bool restore_shell_tioctl()
restore_shell_tioctl() - restore shell terminal settings
Definition scriou.c:57