-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuiltin_command.c
59 lines (53 loc) · 1.51 KB
/
builtin_command.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
#include "builtin_command.h"
int find_last_char_index(const char *__s, char __c) {
int last_index = -1;
for (int i = 0; __s[i] != '\0'; i++) {
if (__s[i] == __c) {
last_index = i;
}
}
return last_index;
}
void exit_command() {
exit(EXIT_SUCCESS);
}
void cd_command(const char* path) {
// not argument
if (path == NULL) {
const char *home_path = getenv("HOME");
if (home_path == NULL) {
perror("Not home");
return;
}
path = (char *)home_path;
}
char result_path[1024];
memset(result_path, '\0', sizeof(result_path));
if (path != NULL && path[0] == '~') {
const char *home_path = getenv("HOME");
if (home_path == NULL) {
perror("Not home");
return;
}
snprintf(result_path, sizeof(result_path), "%s%s", home_path, path+1);
path = result_path;
}
// relative path
if (path[0] != '/') {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
perror("getcwd");
return;
}
if (path[0] == ',' && path[1] == '/') {
snprintf(result_path, sizeof(result_path), "%s%s", cwd, path+1);
path = result_path;
} else if (path[0] == '.' && path[1] == '.') {
cwd[find_last_char_index(cwd, '/')] = '\0';
snprintf(result_path, sizeof(result_path), "%s%s", cwd, path+2);
}
}
if (chdir(path) != 0) {
perror("cd");
}
}