all files: make most variables static and const when possible.
[platform/upstream/coreutils.git] / src / basename.c
1 /* basename -- strip directory and suffix from filenames
2    Copyright (C) 1990, 1991 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; if not, write to the Free Software
16    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 /* Usage: basename name [suffix]
19    NAME is a pathname; SUFFIX is a suffix to strip from it.
20
21    basename /usr/foo/lossage/functions.l
22    => functions.l
23    basename /usr/foo/lossage/functions.l .l
24    => functions
25    basename functions.lisp p
26    => functions.lis */
27
28 #include <stdio.h>
29 #include <sys/types.h>
30 #include "system.h"
31
32 char *basename ();
33 void strip_trailing_slashes ();
34
35 static void remove_suffix ();
36
37 void
38 main (argc, argv)
39      int argc;
40      char **argv;
41 {
42   char *name;
43
44   if (argc == 1 || argc > 3)
45     {
46       fprintf (stderr, "Usage: %s name [suffix]\n", argv[0]);
47       exit (1);
48     }
49
50   strip_trailing_slashes (argv[1]);
51
52   name = basename (argv[1]);
53
54   if (argc == 3)
55     remove_suffix (name, argv[2]);
56
57   puts (name);
58
59   exit (0);
60 }
61
62 /* Remove SUFFIX from the end of NAME if it is there, unless NAME
63    consists entirely of SUFFIX. */
64
65 static void
66 remove_suffix (name, suffix)
67      register char *name, *suffix;
68 {
69   register char *np, *sp;
70
71   np = name + strlen (name);
72   sp = suffix + strlen (suffix);
73
74   while (np > name && sp > suffix)
75     if (*--np != *--sp)
76       return;
77   if (np > name)
78     *np = '\0';
79 }