.
[coreutils.git] / src / basename.c
blobb16cf3ce46e9f0b51df4eed516835eded8bf8a82
1 /* basename -- strip directory and suffix from filenames
2 Copyright (C) 90, 91, 92, 93, 94, 1995 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
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* Usage: basename name [suffix]
19 NAME is a pathname; SUFFIX is a suffix to strip from it.
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 */
28 #include <config.h>
29 #include <stdio.h>
30 #include <sys/types.h>
32 #include "system.h"
33 #include "version.h"
34 #include "long-options.h"
35 #include "error.h"
37 char *basename ();
38 void strip_trailing_slashes ();
40 static void remove_suffix ();
42 /* The name this program was run with. */
43 char *program_name;
45 static void
46 usage (status)
47 int status;
49 if (status != 0)
50 fprintf (stderr, "Try `%s --help' for more information.\n",
51 program_name);
52 else
54 printf ("\
55 Usage: %s NAME [SUFFIX]\n\
56 or: %s OPTION\n\
58 program_name, program_name);
59 printf ("\
60 Print NAME with any leading directory components removed.\n\
61 If specified, also remove a trailing SUFFIX.\n\
62 \n\
63 --help display this help and exit\n\
64 --version output version information and exit\n\
65 ");
67 exit (status);
70 void
71 main (argc, argv)
72 int argc;
73 char **argv;
75 char *name;
77 program_name = argv[0];
79 parse_long_options (argc, argv, "basename", version_string, usage);
81 if (argc == 1 || argc > 3)
83 error (0, 0, "too %s arguments", argc == 1 ? "few" : "many");
84 usage (1);
87 strip_trailing_slashes (argv[1]);
89 name = basename (argv[1]);
91 if (argc == 3)
92 remove_suffix (name, argv[2]);
94 puts (name);
96 exit (0);
99 /* Remove SUFFIX from the end of NAME if it is there, unless NAME
100 consists entirely of SUFFIX. */
102 static void
103 remove_suffix (name, suffix)
104 register char *name, *suffix;
106 register char *np, *sp;
108 np = name + strlen (name);
109 sp = suffix + strlen (suffix);
111 while (np > name && sp > suffix)
112 if (*--np != *--sp)
113 return;
114 if (np > name)
115 *np = '\0';