Replace with FSF version.
[coreutils.git] / lib / argmatch.c
blob5f47711c6daa26c9e85eba0e7c2cea39fd7f26cd
1 /* argmatch.c -- find a match for a string in an array
2 Copyright (C) 1990 Free Software Foundation, Inc.
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.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by David MacKenzie <djm@ai.mit.edu> */
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <sys/types.h>
26 #include <stdio.h>
27 #ifdef STDC_HEADERS
28 #include <string.h>
29 #endif
31 extern char *program_name;
33 /* If ARG is an unambiguous match for an element of the
34 null-terminated array OPTLIST, return the index in OPTLIST
35 of the matched element, else -1 if it does not match any element
36 or -2 if it is ambiguous (is a prefix of more than one element). */
38 int
39 argmatch (arg, optlist)
40 const char *arg;
41 const char *const *optlist;
43 int i; /* Temporary index in OPTLIST. */
44 size_t arglen; /* Length of ARG. */
45 int matchind = -1; /* Index of first nonexact match. */
46 int ambiguous = 0; /* If nonzero, multiple nonexact match(es). */
48 arglen = strlen (arg);
50 /* Test all elements for either exact match or abbreviated matches. */
51 for (i = 0; optlist[i]; i++)
53 if (!strncmp (optlist[i], arg, arglen))
55 if (strlen (optlist[i]) == arglen)
56 /* Exact match found. */
57 return i;
58 else if (matchind == -1)
59 /* First nonexact match found. */
60 matchind = i;
61 else
62 /* Second nonexact match found. */
63 ambiguous = 1;
66 if (ambiguous)
67 return -2;
68 else
69 return matchind;
72 /* Error reporting for argmatch.
73 KIND is a description of the type of entity that was being matched.
74 VALUE is the invalid value that was given.
75 PROBLEM is the return value from argmatch. */
77 void
78 invalid_arg (kind, value, problem)
79 const char *kind;
80 const char *value;
81 int problem;
83 fprintf (stderr, "%s: ", program_name);
84 if (problem == -1)
85 fprintf (stderr, "invalid");
86 else /* Assume -2. */
87 fprintf (stderr, "ambiguous");
88 fprintf (stderr, " %s `%s'\n", kind, value);