-
Notifications
You must be signed in to change notification settings - Fork 749
/
path.c
50 lines (47 loc) · 1.19 KB
/
path.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright 2014 Rui Ueyama. Released under the MIT license.
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <unistd.h>
#include "8cc.h"
// Returns the shortest path for the given full path to a file.
static char *clean(char *p) {
assert(*p == '/');
char buf[PATH_MAX];
char *q = buf;
*q++ = '/';
for (;;) {
if (*p == '/') {
p++;
continue;
}
if (!memcmp("./", p, 2)) {
p += 2;
continue;
}
if (!memcmp("../", p, 3)) {
p += 3;
if (q == buf + 1)
continue;
for (q--; q[-1] != '/'; q--);
continue;
}
while (*p != '/' && *p != '\0')
*q++ = *p++;
if (*p == '/') {
*q++ = *p++;
continue;
}
*q = '\0';
return strdup(buf);
}
}
// Returns the shortest absolute path for the given path.
char *fullpath(char *path) {
static char cwd[PATH_MAX];
if (path[0] == '/')
return clean(path);
if (*cwd == '\0' && !getcwd(cwd, PATH_MAX))
error("getcwd failed: %s", strerror(errno));
return clean(format("%s/%s", cwd, path));
}