merge with 3.4.1
[gnulib.git] / lib / dirname.c
1 /* dirname.c -- return all but the last element in a path
2    Copyright (C) 1990 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 #ifdef STDC_HEADERS
19 #include <stdlib.h>
20 #else
21 char *malloc ();
22 #endif
23 #if defined(STDC_HEADERS) || defined(HAVE_STRING_H)
24 #include <string.h>
25 #ifndef rindex
26 #define rindex strrchr
27 #endif
28 #else
29 #include <strings.h>
30 #endif
31
32 /* Return the leading directories part of PATH,
33    allocated with malloc.  If out of memory, return 0.
34    Assumes that trailing slashes have already been
35    removed.  */
36
37 char *
38 dirname (path)
39      char *path;
40 {
41   char *newpath;
42   char *slash;
43   int length;                   /* Length of result, not including NUL.  */
44
45   slash = rindex (path, '/');
46   if (slash == 0)
47     {
48       /* File is in the current directory.  */
49       path = ".";
50       length = 1;
51     }
52   else
53     {
54       /* Remove any trailing slashes from the result.  */
55       while (slash > path && *slash == '/')
56         --slash;
57
58       length = slash - path + 1;
59     }
60   newpath = malloc (length + 1);
61   if (newpath == 0)
62     return 0;
63   strncpy (newpath, path, length);
64   newpath[length] = 0;
65   return newpath;
66 }