]> git.saurik.com Git - apple/libc.git/blame - gen/FreeBSD/dirname.c
Libc-825.24.tar.gz
[apple/libc.git] / gen / FreeBSD / dirname.c
CommitLineData
1f2f436a
A
1/* $OpenBSD: dirname.c,v 1.13 2005/08/08 08:05:33 espie Exp $ */
2
5b2abdfb 3/*
1f2f436a 4 * Copyright (c) 1997, 2004 Todd C. Miller <Todd.Miller@courtesan.com>
5b2abdfb 5 *
1f2f436a
A
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
5b2abdfb 9 *
1f2f436a
A
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
5b2abdfb
A
17 */
18
9385eb3d 19#include <sys/cdefs.h>
1f2f436a 20__FBSDID("$FreeBSD: src/lib/libc/gen/dirname.c,v 1.8 2008/11/03 05:19:45 delphij Exp $");
5b2abdfb
A
21
22#include <errno.h>
23#include <libgen.h>
9385eb3d 24#include <stdlib.h>
5b2abdfb
A
25#include <string.h>
26#include <sys/param.h>
5b2abdfb 27
ad3c9f2a
A
28#if __DARWIN_UNIX03
29#define const /**/
30#endif
31
5b2abdfb 32char *
1f2f436a 33dirname(const char *path)
5b2abdfb 34{
1f2f436a
A
35 static char *dname = NULL;
36 size_t len;
9385eb3d 37 const char *endp;
5b2abdfb 38
1f2f436a
A
39 if (dname == NULL) {
40 dname = (char *)malloc(MAXPATHLEN);
41 if (dname == NULL)
9385eb3d 42 return(NULL);
5b2abdfb
A
43 }
44
45 /* Empty or NULL string gets treated as "." */
46 if (path == NULL || *path == '\0') {
1f2f436a
A
47 dname[0] = '.';
48 dname[1] = '\0';
49 return (dname);
5b2abdfb
A
50 }
51
1f2f436a 52 /* Strip any trailing slashes */
5b2abdfb
A
53 endp = path + strlen(path) - 1;
54 while (endp > path && *endp == '/')
55 endp--;
56
57 /* Find the start of the dir */
58 while (endp > path && *endp != '/')
59 endp--;
60
61 /* Either the dir is "/" or there are no slashes */
62 if (endp == path) {
1f2f436a
A
63 dname[0] = *endp == '/' ? '/' : '.';
64 dname[1] = '\0';
65 return (dname);
5b2abdfb 66 } else {
1f2f436a 67 /* Move forward past the separating slashes */
5b2abdfb
A
68 do {
69 endp--;
70 } while (endp > path && *endp == '/');
71 }
72
1f2f436a
A
73 len = endp - path + 1;
74 if (len >= MAXPATHLEN) {
5b2abdfb 75 errno = ENAMETOOLONG;
1f2f436a 76 return (NULL);
5b2abdfb 77 }
1f2f436a
A
78 memcpy(dname, path, len);
79 dname[len] = '\0';
80 return (dname);
5b2abdfb 81}