File: get_value.c

package info (click to toggle)
account-utils 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 836 kB
  • sloc: ansic: 8,789; xml: 1,584; sh: 77; makefile: 10
file content (78 lines) | stat: -rw-r--r-- 1,761 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// SPDX-License-Identifier: GPL-2.0-or-later

#include "config.h"

#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

#include "basics.h"
#include "get_value.h"

/* prompt the user with the name of the field being changed and the
   current value.
   return value:
   0   -> success
   < 0 -> error, -errno as code
   input argument:
   NULL  -> Ctrl-D was pressed
   ""    -> Field was cleard by user. User can enter a space or
            "none" to do this.
   def   -> User entered only <return>.
   input -> User entered something new . */
int
get_value(const char *def, const char *prompt, char **input)
{
  char buf[BUFSIZ];
  char *cp;

  *input = NULL;

  printf("\t%s [%s]: ", prompt, strempty(def));
  if (fgets(buf, sizeof(buf), stdin) != buf)
    {
      /* print newline to get defined output.  */
      printf("\n");
      return 0;
    }

  if ((cp = strchr(buf, '\n')) != NULL)
    *cp = '\0';

  if (buf[0]) /* something is entered */
    {
      /* if none is entered, return an empty string. If somebody
	 wishes to enter "none", he as to add a space.  */
      if(strcasecmp("none", buf) == 0)
	{
	  *input = strdup("");
	  if (*input == NULL)
	    return -ENOMEM;
	  return 0;
	}

      /* Remove leading and trailing whitespace. This also
	 makes it possible to change the field to empty or
	 "none" by entering a space.  */

      /* cp should point to the trailing '\0'.  */
      cp = &buf[strlen(buf)];

      while(--cp >= buf && isspace(*cp))
	;
      *++cp = '\0';

      cp = buf;
      while (*cp && isspace(*cp))
	cp++;
      *input = strdup(cp);
      if (*input == NULL)
	return -ENOMEM;
      return 0;
    }
  *input = strdup(strempty(def));
  if (*input == NULL)
    return -ENOMEM;
  return 0;
}