1 /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 ** Pathname subroutines.
8 ** Brendan Eich, 8/29/95
11 #include <sys/types.h>
22 #ifdef USE_REENTRANT_LIBC
37 fail(char *format
, ...)
42 #ifdef USE_REENTRANT_LIBC
47 fprintf(stderr
, "%s: ", program
);
49 vfprintf(stderr
, format
, ap
);
53 #ifdef USE_REENTRANT_LIBC
55 fprintf(stderr
, ": %s", r_strerror_r
);
57 fprintf(stderr
, ": %s", strerror(errno
));
66 getcomponent(char *path
, char *name
)
75 } while (*path
!= '/' && *path
!= '\0');
84 #include <sys/param.h>
86 ** The static buffer in Unixware's readdir is too small.
88 struct dirent
*readdir(DIR *d
)
90 static struct dirent
*buf
= NULL
;
93 buf
= (struct dirent
*) malloc(sizeof(struct dirent
) + MAXPATHLEN
);
94 return(readdir_r(d
, buf
));
107 fail("cannot read parent directory");
109 if (!(ep
= readdir(dp
)))
110 fail("cannot find current directory");
111 if (ep
->D_INO
== ino
)
114 name
= xstrdup(ep
->d_name
);
122 void *p
= malloc(size
);
124 fail("cannot allocate %u bytes", size
);
131 return strcpy(xmalloc(strlen(s
) + 1), s
);
135 xbasename(char *path
)
139 while ((cp
= strrchr(path
, '/')) && cp
[1] == '\0')
141 if (!cp
) return path
;
149 fail("cannot change directory to %s", dir
);
153 relatepaths(char *from
, char *to
, char *outpath
)
159 assert(*from
== '/' && *to
== '/');
160 for (cp
= to
, cp2
= from
; *cp
== *cp2
; cp
++, cp2
++)
163 while (cp
[-1] != '/')
166 /* closest common ancestor is /, so use full pathname */
167 len
= strlen(strcpy(outpath
, to
));
168 if (outpath
[len
] != '/') {
169 outpath
[len
++] = '/';
174 while ((cp2
= getcomponent(cp2
, buf
)) != 0) {
175 strcpy(outpath
+ len
, "../");
178 while ((cp
= getcomponent(cp
, buf
)) != 0) {
179 sprintf(outpath
+ len
, "%s/", buf
);
180 len
+= strlen(outpath
+ len
);
187 reversepath(char *inpath
, char *name
, int len
, char *outpath
)
193 cp
= strcpy(outpath
+ PATH_MAX
- (len
+ 1), name
);
195 while ((cp2
= getcomponent(cp2
, buf
)) != 0) {
196 if (strcmp(buf
, ".") == 0)
198 if (strcmp(buf
, "..") == 0) {
199 if (stat(".", &sb
) < 0)
200 fail("cannot stat current directory");
201 name
= ino2name(sb
.st_ino
);
210 strncpy(cp
, "../", 3);