blob: 3d8280a032d94f23951baa40d374aff438e9f8e4 [file] [log] [blame]
vlm1f1d8cb2004-08-13 16:58:19 +00001#include <asn1c_compat.h>
2
3#include <string.h>
4#include <errno.h>
5
6#ifdef HAVE_SYS_PARAM_H
7#include <sys/param.h> /* For MAXPATHLEN */
8#endif
9
10#ifndef MAXPATHLEN
11#define MAXPATHLEN 1024
12#endif
13
14char *
15a1c_basename(const char *path) {
16 static char strbuf[MAXPATHLEN];
17 const char *pend;
18 const char *name;
19
20 pend = path + strlen(path);
21 if(pend == path) {
22 strcpy(strbuf, ".");
23 return strbuf;
24 }
25
26 /* Skip tailing slashes */
27 for(pend--; pend > path && *pend == '/'; pend--);
28
29 if(pend == path && *path == '/') {
30 strcpy(strbuf, "/");
31 return strbuf;
32 }
33
34 for(name = pend; name > path && name[-1] != '/'; name--);
35
36 if((pend - name) >= sizeof(strbuf) - 1) {
37 errno = ENAMETOOLONG;
38 return 0;
39 }
40
41 memcpy(strbuf, name, pend - name + 1);
42 strbuf[pend - name + 1] = '\0';
43
44 return strbuf;
45}
46
47
48char *
49a1c_dirname(const char *path) {
50 static char strbuf[MAXPATHLEN];
51 const char *pend;
52 const char *last = 0;
53 int in_slash = 0;
54
55 /* One-pass determination of the last char of the pathname */
56 for(pend = path; ; pend++) {
57 printf("-%c", *pend);
58 switch(*pend) {
59 case '\0': break;
60 case '/':
61 if(!in_slash) {
62 last = pend;
63 in_slash = 1;
64 }
65 continue;
66 default:
67 if(in_slash) in_slash = 0;
68 continue;
69 }
70 break;
71 }
72 printf("\n");
73
74 if(last <= path) {
75 strcpy(strbuf, *path == '/' ? "/" : ".");
76 return strbuf;
77 }
78
79 if(!last) {
80 strcpy(strbuf, "/");
81 return strbuf;
82 }
83
84 if((last - path) >= sizeof(strbuf)) {
85 errno = ENAMETOOLONG;
86 return 0;
87 }
88
89 memcpy(strbuf, path, last - path);
90 strbuf[last - path] = '\0';
91
92 return strbuf;
93}
94