libite 2.6.1
yorn.c
Go to the documentation of this file.
1/* Safe yes-or-no with prompt
2 *
3 * Copyright (c) 2009-2021 Joachim Wiberg <troglobit@gmail.com>
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
24
25#include <stdio.h>
26#include <stdio_ext.h> /* __fpurge() */
27#include <stdarg.h>
28#include <termios.h>
29#include <unistd.h>
30
31static char rawgetch(void)
32{
33 struct termios savemodes, modmodes;
34 char val;
35
36 if (!isatty(STDIN_FILENO))
37 return getchar();
38
39 /* Backup terminal settings. */
40 if (tcgetattr(STDIN_FILENO, &savemodes) < 0) {
41 return -1;
42 }
43
44 /* "stty cbreak -echo" */
45 modmodes = savemodes;
46 modmodes.c_lflag &= ~ICANON;
47 modmodes.c_lflag &= ~ECHO;
48 modmodes.c_cc[VMIN] = 1;
49 modmodes.c_cc[VTIME] = 0;
50
51 /* Set terminal in raw mode. */
52 if (tcsetattr(STDIN_FILENO, TCSANOW, &modmodes) < 0) {
53 tcsetattr(STDIN_FILENO, TCSANOW, &savemodes);
54 return -1;
55 }
56
57 val = getchar();
58
59 /* Restore terminal to previous state. */
60 tcsetattr(STDIN_FILENO, TCSANOW, &savemodes);
61
62 return val;
63}
64
74int yorn(const char *fmt, ...)
75{
76 va_list ap;
77 char yorn;
78
79 va_start(ap, fmt);
80 vfprintf(stderr, fmt, ap);
81 va_end(ap);
82
83 __fpurge(stdin);
84 yorn = rawgetch();
85 printf("%c\n", yorn);
86 fflush(stdout);
87 if (yorn != 'y' && yorn != 'Y')
88 return 0;
89
90 return 1;
91}
92
int yorn(const char *fmt,...)
Definition yorn.c:74