1 /* dirname.c -- return all but the last element in a file name
3 Copyright (C) 1990, 1998, 2000, 2001, 2003, 2004, 2005, 2006 Free Software
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software Foundation,
18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
29 /* Return the length of the prefix of FILE that will be used by
30 dir_name. If FILE is in the working directory, this returns zero
31 even though `dir_name (FILE)' will return ".". Works properly even
32 if there are trailing slashes (by effectively ignoring them). */
35 dir_len (char const *file)
37 size_t prefix_length = FILE_SYSTEM_PREFIX_LEN (file);
40 /* Advance prefix_length beyond important leading slashes. */
41 prefix_length += (prefix_length != 0
42 ? (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
43 && ISSLASH (file[prefix_length]))
45 ? ((DOUBLE_SLASH_IS_DISTINCT_ROOT
46 && ISSLASH (file[1]) && ! ISSLASH (file[2])
50 /* Strip the basename and any redundant slashes before it. */
51 for (length = last_component (file) - file;
52 prefix_length < length; length--)
53 if (! ISSLASH (file[length - 1]))
59 /* In general, we can't use the builtin `dirname' function if available,
60 since it has different meanings in different environments.
61 In some environments the builtin `dirname' modifies its argument.
63 Return the leading directories part of FILE, allocated with xmalloc.
64 Works properly even if there are trailing slashes (by effectively
65 ignoring them). Unlike POSIX dirname(), FILE cannot be NULL.
67 If lstat (FILE) would succeed, then { chdir (dir_name (FILE));
68 lstat (base_name (FILE)); } will access the same file. Likewise,
69 if the sequence { chdir (dir_name (FILE));
70 rename (base_name (FILE), "foo"); } succeeds, you have renamed FILE
71 to "foo" in the same directory FILE was in. */
74 dir_name (char const *file)
76 size_t length = dir_len (file);
77 bool append_dot = (length == 0
78 || (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE
79 && length == FILE_SYSTEM_PREFIX_LEN (file)
80 && file[2] != '\0' && ! ISSLASH (file[2])));
81 char *dir = xmalloc (length + append_dot + 1);
82 memcpy (dir, file, length);