1
/* dirname.c -- return all but the last element in a path
2
Copyright 1990, 1998, 2000, 2001, 2003 Free Software Foundation, Inc.
1
/* dirname.c -- return all but the last element in a file name
3
Copyright (C) 1990, 1998, 2000, 2001, 2003, 2004, 2005 Free Software
4
6
This program is free software; you can redistribute it and/or modify
5
7
it under the terms of the GNU General Public License as published by
14
16
You should have received a copy of the GNU General Public License
15
17
along with this program; if not, write to the Free Software Foundation,
16
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
19
21
# include <config.h>
22
#if STDC_HEADERS || HAVE_STRING_H
26
24
#include "dirname.h"
27
27
#include "xalloc.h"
29
/* Return the length of `dirname (PATH)', or zero if PATH is
29
/* Return the length of `dirname (FILE)', or zero if FILE is
30
30
in the working directory. Works properly even if
31
31
there are trailing slashes (by effectively ignoring them). */
33
dir_len (char const *path)
33
dir_len (char const *file)
35
size_t prefix_length = FILESYSTEM_PREFIX_LEN (path);
35
size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file);
38
38
/* Strip the basename and any redundant slashes before it. */
39
for (length = base_name (path) - path; prefix_length < length; length--)
40
if (! ISSLASH (path[length - 1]))
39
for (length = base_name (file) - file; prefix_length < length; length--)
40
if (! ISSLASH (file[length - 1]))
43
43
/* But don't strip the only slash from "/". */
44
return prefix_length + ISSLASH (path[prefix_length]);
44
return prefix_length + ISSLASH (file[prefix_length]);
47
/* Return the leading directories part of PATH,
47
/* Return the leading directories part of FILE,
48
48
allocated with xmalloc.
49
49
Works properly even if there are trailing slashes
50
50
(by effectively ignoring them). */
53
dir_name (char const *path)
53
dir_name (char const *file)
55
size_t length = dir_len (path);
56
int append_dot = (length == FILESYSTEM_PREFIX_LEN (path));
57
char *newpath = xmalloc (length + append_dot + 1);
58
memcpy (newpath, path, length);
55
size_t length = dir_len (file);
56
bool append_dot = (length == FILE_SYSTEM_PREFIX_LEN (file));
57
char *dir = xmalloc (length + append_dot + 1);
58
memcpy (dir, file, length);
60
newpath[length++] = '.';
65
65
#ifdef TEST_DIRNAME
108
108
buff[MAX_BUFF_LEN] = 0;
109
109
while (fgets (buff, MAX_BUFF_LEN, stdin) && buff[0])
111
char path[MAX_BUFF_LEN];
111
char file[MAX_BUFF_LEN];
112
112
char expected_result[MAX_BUFF_LEN];
113
113
char const *result;
114
sscanf (buff, "%s %s", path, expected_result);
115
result = dir_name (path);
114
sscanf (buff, "%s %s", file, expected_result);
115
result = dir_name (file);
116
116
if (strcmp (result, expected_result))
117
printf ("%s: got %s, expected %s\n", path, result, expected_result);
117
printf ("%s: got %s, expected %s\n", file, result, expected_result);