1 /* dirname.c -- return all but the last element in a path
2 Copyright (C) 1990, 1998 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 Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
17
18 #if HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21
22 /*******************************************************
23 * THIS IS A MODIFIED dirname IMPLEMENTATION:
24 * - sitecopy wants "" if there is no directory name,
25 * standard GNU implementation gives us "."
26 * - sitecopy wants the trailing slash.
27 *******************************************************/
28
29 #ifdef STDC_HEADERS
30 # include <stdlib.h>
31 #else
32 char *malloc ();
33 #endif
34 #if defined STDC_HEADERS || defined HAVE_STRING_H
35 # include <string.h>
36 #else
37 # include <strings.h>
38 # ifndef strrchr
39 # define strrchr rindex
40 # endif
41 #endif
42
43 #include "dirname.h"
44
45 /* Return the leading directories part of PATH,
46 allocated with malloc. If out of memory, return 0.
47 Assumes that trailing slashes have already been
48 removed. */
49
50 char *
dir_name(const char * path)51 dir_name (const char *path)
52 {
53 char *newpath;
54 char *slash;
55 int length; /* Length of result, not including NUL. */
56
57 slash = strrchr (path, '/');
58 if (slash == 0)
59 {
60 /* File is in the current directory. */
61 path = "";
62 length = 0;
63 }
64 else
65 {
66 /* Remove any trailing slashes from the result.
67 while (slash > path && *slash == '/')
68 --slash; */
69
70 length = slash - path + 1;
71 }
72 newpath = (char *) malloc (length + 1);
73 if (newpath == 0)
74 return 0;
75 strncpy (newpath, path, length);
76 newpath[length] = 0;
77 return newpath;
78 }
79