/*
* SPDX-FileCopyrightText: 1992 - 1994, Julianne Frances Haugh
* SPDX-FileCopyrightText: 2007 - 2008, Nicolas François
+ * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
*
* SPDX-License-Identifier: BSD-3-Clause
*/
-/*
- * Common code for yes/no prompting
- *
- * Used by pwck.c and grpck.c
- */
#include <config.h>
#ident "$Id$"
+#include <stdbool.h>
#include <stdio.h>
+#include <stdlib.h>
#include "prototypes.h"
+
/*
- * yes_or_no - get answer to question from the user
+ * Synopsis
+ * bool yes_or_no(bool read_only);
+ *
+ * Arguments
+ * read_only
+ * In read-only mode, all questions are answered "no". It
+ * will print "No" to stdout.
*
- * It returns false if no.
+ * Description
+ * After a yes/no question, this function gets the answer from the
+ * user.
*
- * If the read_only flag is set, it will print No, and will return
- * false.
+ * Calls to this function will normally be preceeded by a prompt on
+ * stdout, so we should fflush(3).
+ *
+ * Return value
+ * false "no"
+ * true "yes"
+ *
+ * See also
+ * rpmatch(3)
*/
-bool yes_or_no (bool read_only)
+
+
+#if !defined(HAVE_RPMATCH)
+static int rpmatch(const char *response);
+#endif
+
+
+bool
+yes_or_no(bool read_only)
{
- int c;
- bool result;
+ bool ret;
+ char *buf;
- /*
- * In read-only mode all questions are answered "no".
- */
if (read_only) {
- (void) puts (_("No"));
+ puts(_("No"));
return false;
}
- /*
- * Typically, there's a prompt on stdout, sometimes unflushed.
- */
- (void) fflush (stdout);
+ fflush(stdout);
- /*
- * Get a line and see what the first character is.
- */
- c = fgetc(stdin);
- /* TODO: use gettext */
- result = (c == 'y' || c == 'Y');
+ ret = false;
+ if (getline(&buf, NULL, stdin) != NULL)
+ ret = rpmatch(buf) == 1;
- while (c != '\n' && c != EOF)
- c = fgetc(stdin);
-
- return result;
+ free(buf);
+ return ret;
}
+
+#if !defined(HAVE_RPMATCH)
+static int
+rpmatch(const char *response)
+{
+ if (response[0] == 'y' || response[0] == 'Y')
+ return 1;
+
+ if (response[0] == 'n' || response[0] == 'n')
+ return 0;
+
+ return -1;
+}
+#endif