1 /* argmatch.c -- find a match for a string in an array
2 Copyright (C) 1990, 1997 Free Software Foundation, Inc.
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; see the file COPYING.
16 If not, write to the Free Software Foundation,
17 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18
19 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
20
21 #if HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include <argmatch.h>
26
27 #include <sys/types.h>
28
29 #include <stdio.h>
30 #if HAVE_STRING_H
31 # include <string.h>
32 #else
33 # include <strings.h>
34 #endif
35
36 /* If ARG is an unambiguous match for an element of the
37 null-terminated array OPTLIST, return the index in OPTLIST
38 of the matched element, else -1 if it does not match any element
39 or -2 if it is ambiguous (is a prefix of more than one element). */
40
41 int
argmatch(arg,optlist)42 argmatch (arg, optlist)
43 const char *arg;
44 const char *const *optlist;
45 {
46 int i; /* Temporary index in OPTLIST. */
47 size_t arglen; /* Length of ARG. */
48 int matchind = -1; /* Index of first nonexact match. */
49 int ambiguous = 0; /* If nonzero, multiple nonexact match(es). */
50
51 arglen = strlen (arg);
52
53 /* Test all elements for either exact match or abbreviated matches. */
54 for (i = 0; optlist[i]; i++)
55 {
56 if (!strncmp (optlist[i], arg, arglen))
57 {
58 if (strlen (optlist[i]) == arglen)
59 /* Exact match found. */
60 return i;
61 else if (matchind == -1)
62 /* First nonexact match found. */
63 matchind = i;
64 else
65 /* Second nonexact match found. */
66 ambiguous = 1;
67 }
68 }
69 if (ambiguous)
70 return -2;
71 else
72 return matchind;
73 }
74
75 /* Error reporting for argmatch.
76 KIND is a description of the type of entity that was being matched.
77 VALUE is the invalid value that was given.
78 PROBLEM is the return value from argmatch. */
79
80 void
invalid_arg(kind,value,problem)81 invalid_arg (kind, value, problem)
82 const char *kind;
83 const char *value;
84 int problem;
85 {
86 fprintf (stderr, "%s: ", program_name);
87 if (problem == -1)
88 fprintf (stderr, "invalid");
89 else /* Assume -2. */
90 fprintf (stderr, "ambiguous");
91 fprintf (stderr, " %s `%s'\n", kind, value);
92 }
93