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

From: Alan Potteiger <alanpotteiger_AT_gmail.com>
Date: Sun, 20 Nov 2022 13:17:18 +0100

On Sun, Nov 20, 2022 at 2:17 AM Sebastian LaVine <mail_AT_smlavine.com> wrote:
>
> This only reads a single character, not a line as the standard states.
> If the user responds with 'y\n', then that '\n' is going to be read if
> the program takes any more input. I suggest using getline(3) instead.
>
> [0]: https://www.man7.org/linux/man-pages/man1/cp.1p.html
>

My mistake. I misunderstood how the buffering works in stdio, I played
with it and
saw exactly what you mean. Switched to getline(3).

---
 Makefile           |  1 +
 libutil/promptyn.c | 26 ++++++++++++++++++++++++++
 util.h             |  1 +
 3 files changed, 28 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..b63bfaa
--- /dev/null
+++ b/libutil/promptyn.c
_AT_@ -0,0 +1,26 @@
+/* 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;
+ char *linep = NULL;
+ size_t linecapp = 1;
+
+ va_start(ap, promptfmt);
+ vfprintf(stderr, promptfmt, ap);
+ va_end(ap);
+
+ fprintf(stderr, " (y/n [n]): ");
+ getline(&linep, &linecapp, stdin);
+ switch (*linep) {
+ 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 Sun Nov 20 2022 - 13:17:18 CET

This archive was generated by hypermail 2.3.0 : Sun Nov 20 2022 - 15:24:32 CET