-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwarp.c
More file actions
104 lines (102 loc) · 3.31 KB
/
warp.c
File metadata and controls
104 lines (102 loc) · 3.31 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "headers.h"
void warp(char* input, bool pr){
int cnt = 0;
char* temp = (char*) malloc(4096);
strcpy(temp, input);
char* dir;
char* here;
while(here = (char*) strtok_r(temp, " ", &temp)){
dir = here;
++cnt;
}
int len = strlen(dir);
if(len && dir[len - 1] == '\n')
dir[len - 1] = '\0';
// cnt <= 2
if(cnt == 1){
// go to home dir
strcpy(predir, curdir);
strcpy(curdir, homedir);
chdir(curdir);
getcwd(curdir, N);
if(pr)
printf("%s\n", curdir);
}
else{
strcpy(temp, input);
cnt = 0;
while(here = strtok_r(temp, " ", &temp)){
dir = here;
int len = strlen(dir);
if(len && dir[len - 1] == '\n')
dir[len - 1] = '\0';
if(cnt){
// handle ., .., ~, -, any dir
if(!strcmp("~", dir)){
strcpy(predir, curdir);
strcpy(curdir, homedir);
chdir(curdir);
}
else if(!strcmp("-", dir)){
if(!strcmp(predir, "-1")){
// nothing in history
// error handling
printf("OLDPWD not set\n");
continue;
}
else{
char what[4096];
strcpy(what, curdir);
strcpy(curdir, predir);
strcpy(predir, what);
chdir(curdir);
}
}
// Check if the path is relative or absolute
else if(dir[0] == '/'){
// absolute
if(!chdir(dir)){
strcpy(predir, curdir);
strcpy(curdir, dir);
chdir(curdir);
}
else{
printf("Given destination does not exist\n");
continue;
}
}
else{
// relative
if(dir[0] == '~'){
char actual[4096];
strcpy(actual, homedir);
int j = strlen(homedir);
for(int i = 1; i < strlen(dir); ++i)
actual[j++] = dir[i];
actual[j] = '\0';
strcpy(curdir, actual);
chdir(curdir);
}
else{
char her[4096];
strcpy(her, curdir);
strcat(curdir, "/");
strcat(curdir, dir);
if(!chdir(curdir)){
strcpy(predir, her);
chdir(curdir);
}
else{
printf("Given destination does not exist\n");
continue;
}
}
}
getcwd(curdir, N);
if(pr)
printf("%s\n", curdir);
}
++cnt;
}
}
}