-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcd.c
60 lines (43 loc) · 1.02 KB
/
cd.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
51
52
53
54
55
56
57
58
59
60
#include "cd.h"
#include "headers.h"
int tichnas_cd(char* root, char* cwd, char* prevwd, char* newdir) {
char newwd[1024] = "";
if (newdir == NULL) {
sprintf(newwd, "%s", root);
} else if (!strcmp(newdir, "-")) {
if (prevwd[0] == '.') {
printf("%s\n", cwd);
return 0;
}
int isRelative = 0;
if (chdir(prevwd) < 0) {
perror("Error");
return -1;
}
for (int i = 0;; i++) {
if (root[i] == '\0') {
isRelative = 1;
break;
}
if (prevwd[i] == '\0' || prevwd[i] != root[i]) break;
}
if (isRelative) {
prevwd += strlen(root) - 1;
prevwd[0] = '~';
}
printf("%s\n", prevwd);
return 0;
} else if (newdir[0] == '/') {
sprintf(newwd, "%s", newdir);
} else {
strcat(newwd, newdir[0] == '~' ? root : cwd);
if (newdir[0] != '~') strcat(newwd, "/");
strcat(newwd, newdir + (newdir[0] == '~'));
}
strcpy(prevwd, cwd);
if (chdir(newwd) < 0) {
perror("Error");
return -1;
}
return 0;
}