Go to most recent revision | Details | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
1882 | clevermous | 1 | /* Copyright (C) 1998 DJ Delorie, see COPYING.DJ for details */ |
2 | /* Copyright (C) 1997 DJ Delorie, see COPYING.DJ for details */ |
||
3 | #include |
||
4 | #include |
||
5 | #include |
||
6 | |||
7 | char * |
||
8 | dirname (const char *fname) |
||
9 | { |
||
10 | const char *p = fname; |
||
11 | const char *slash = NULL; |
||
12 | |||
13 | if (fname) |
||
14 | { |
||
15 | size_t dirlen; |
||
16 | char * dirpart; |
||
17 | |||
18 | if (*fname && fname[1] == ':') |
||
19 | { |
||
20 | slash = fname + 1; |
||
21 | p += 2; |
||
22 | } |
||
23 | |||
24 | /* Find the rightmost slash. */ |
||
25 | while (*p) |
||
26 | { |
||
27 | if (*p == '/' || *p == '\\') |
||
28 | slash = p; |
||
29 | p++; |
||
30 | } |
||
31 | |||
32 | if (slash == NULL) |
||
33 | { |
||
34 | fname = "."; |
||
35 | dirlen = 1; |
||
36 | } |
||
37 | else |
||
38 | { |
||
39 | /* Remove any trailing slashes. */ |
||
40 | while (slash > fname && (slash[-1] == '/' || slash[-1] == '\\')) |
||
41 | slash--; |
||
42 | |||
43 | /* How long is the directory we will return? */ |
||
44 | dirlen = slash - fname + (slash == fname || slash[-1] == ':'); |
||
45 | if (*slash == ':' && dirlen == 1) |
||
46 | dirlen += 2; |
||
47 | } |
||
48 | |||
49 | dirpart = (char *)malloc (dirlen + 1); |
||
50 | if (dirpart != NULL) |
||
51 | { |
||
52 | strncpy (dirpart, fname, dirlen); |
||
53 | if (slash && *slash == ':' && dirlen == 3) |
||
54 | dirpart[2] = '.'; /* for "x:foo" return "x:." */ |
||
55 | dirpart[dirlen] = '\0'; |
||
56 | } |
||
57 | |||
58 | return dirpart; |
||
59 | } |
||
60 | |||
61 | return NULL; |
||
62 | } |