*** empty log message ***
[coreutils.git] / lib / argmatch.c
blobaa5593329765506faf3a4f67c52f1d5fff2c8f54
1 /* argmatch.c -- find a match for a string in an array
2 Copyright (C) 1990, 1997 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; see the file COPYING.
16 If not, write to the Free Software Foundation,
17 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
21 #if HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #include <argmatch.h>
27 #include <sys/types.h>
29 #include <stdio.h>
30 #if HAVE_STRING_H
31 # include <string.h>
32 #else
33 # include <strings.h>
34 #endif
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). */
41 int
42 argmatch (arg, optlist)
43 const char *arg;
44 const char *const *optlist;
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). */
51 arglen = strlen (arg);
53 /* Test all elements for either exact match or abbreviated matches. */
54 for (i = 0; optlist[i]; i++)
56 if (!strncmp (optlist[i], arg, arglen))
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;
69 if (ambiguous)
70 return -2;
71 else
72 return matchind;
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. */
80 void
81 invalid_arg (kind, value, problem)
82 const char *kind;
83 const char *value;
84 int problem;
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);