forked from rui314/8cc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath.c
More file actions
54 lines (51 loc) · 1.3 KB
/
path.c
File metadata and controls
54 lines (51 loc) · 1.3 KB
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
51
52
53
54
// Copyright 2014 Rui Ueyama <rui314@gmail.com>
// This program is free software licensed 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];
int level = 0;
char *q = buf;
*q++ = '/';
for (;;) {
if (*p == '/') {
p++;
continue;
}
if (!memcmp("./", p, 2)) {
p += 2;
continue;
}
if (!memcmp("../", p, 3)) {
p += 3;
if (level == 0)
continue;
for (q--; q[-1] != '/'; q--);
level--;
continue;
}
while (*p != '/' && *p != '\0')
*q++ = *p++;
if (*p == '/') {
*q++ = *p++;
level++;
continue;
}
*q = '\0';
return format("%s", 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));
}