[hackers] [sbase][PATCH 1/2] libutil: Implement a simple yes/no prompt

From: Alan Potteiger <alanpotteiger_AT_gmail.com>
Date: Sat, 19 Nov 2022 22:42:58 +0100

`promptyn` fills the requirement for the prompts that need implemented
in `cp`, `mv`, and `rm` through the `-i` flag.

The function accepts a string that is emitted when no is
chosen, a format string for the prompt, and a list of fields for the format
string. It returns 1 for a no response and 0 for a yes response.
---
 Makefile           |  1 +
 libutil/promptyn.c | 23 +++++++++++++++++++++++
 util.h             |  1 +
 3 files changed, 25 insertions(+)
 create mode 100644 libutil/promptyn.c
diff --git a/Makefile b/Makefile
index 3243b1c..0a5c930 100644
--- a/Makefile
+++ b/Makefile
_AT_@ -63,6 +63,7 @@ LIBUTILSRC =\
        libutil/mkdirp.c\
        libutil/mode.c\
        libutil/parseoffset.c\
+       libutil/promptyn.c\
        libutil/putword.c\
        libutil/reallocarray.c\
        libutil/recurse.c\
diff --git a/libutil/promptyn.c b/libutil/promptyn.c
new file mode 100644
index 0000000..0214ee3
--- /dev/null
+++ b/libutil/promptyn.c
_AT_@ -0,0 +1,23 @@
+/* See LICENSE file for copyright and license details. */
+#include <stdio.h>
+#include <stdarg.h>
+
+int
+promptyn(const char *nomsg, const char *promptfmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, promptfmt);
+       vfprintf(stderr, promptfmt, ap);
+       va_end(ap);
+
+       fprintf(stderr, " (y/n [n]): ");
+       switch (getchar()) {
+       case 'y': case 'Y':
+               return 0;
+       default:
+               fprintf(stderr, "%s\n", nomsg);
+               return 1;
+       }
+}
+
diff --git a/util.h b/util.h
index 8d5004b..6060d95 100644
--- a/util.h
+++ b/util.h
_AT_@ -73,6 +73,7 @@ int concat(int, const char *, int, const char *);
 /* misc */
 void enmasse(int, char **, int (*)(const char *, const char *, int));
+int promptyn(const char *, const char *, ...);
 void fnck(const char *, const char *, int (*)(const char *, const
char *, int), int);
 mode_t getumask(void);
 char *humansize(off_t);
--
2.37.3
Received on Sat Nov 19 2022 - 22:42:58 CET

This archive was generated by hypermail 2.3.0 : Sat Nov 19 2022 - 22:48:31 CET