-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell_cd.c
81 lines (64 loc) · 2.03 KB
/
shell_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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "shell_cd.h"
#include "shell.h"
// char* current_working_dir;
void* dir_ptr;
int shell_cd(char** args, char* root) {
if (args[1] == NULL) {
chdir(root);
}
else {
char* token = strtok(args[1], "/");
if (args[1][0] == '/') {
int error = chdir(args[1]);
if (error < 0) {
perror("Error");
}
// printf("%s\n", token);
}
else {
while (token != NULL) {
char* cwd = (char*)malloc(8192);
getcwd(cwd, 8192);
if (strcmp(token, "~") == 0) {
chdir(root);
}
else if (strcmp(token, "..") == 0) {
char* prev_dir = (char*)malloc(8192);
int length = strlen(cwd);
int i = length;
for (i = length - 1; i >=0; i--) {
if (cwd[i] == '/') {
break;
}
}
for (int j = 0; j < i; j++) {
prev_dir[j] = cwd[j];
}
prev_dir[i] = '\0';
int error = chdir(prev_dir);
if (error < 0) {
perror("Error");
}
free(prev_dir);
}
else if (strcmp(token, ".") == 0) {
chdir(cwd);
}
else {
char* dir = (char*)malloc(8192);
strcat(dir, cwd);
strcat(dir, "/");
strcat(dir, token);
int error = chdir(dir);
if (error < 0) {
perror("Error");
}
}
free(cwd);
token = strtok(NULL, "/");
}
}
}
// getcwd(current_working_dir, 250);
// sprintf(dir_ptr, "%s", current_working_dir);
}