-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.c
More file actions
113 lines (99 loc) · 2.89 KB
/
Copy pathutils.c
File metadata and controls
113 lines (99 loc) · 2.89 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
105
106
107
108
109
110
111
112
113
#include "utils.h"
#include "signals.h"
void initialize_everything() {
printf(ANSI_CLEAR);
{
const char rocket[] =
" ^ \n\
/^\\\n\
|-|\n\
| |\n\
|S|\n\
|E|\n\
|A|\n\
|S|\n\
|H|\n\
|E|\n\
/|L|\\\n\
/ |L| \\\n\
| | | |\n\
`-\"\"\"-`\n\
";
fputs(rocket, stdout);
}
printf(ANSI_YELLOW_BOLD "\n\t***\tWelcome to SeaShell\t***\t\n" ANSI_DEFAULT);
initialize_signals();
prompt();
}
void prompt() {
printf("\nSeaShell > ");
fflush(stdout);
}
char **tokenize(char *line, char delim) {
char **tokens = (char **)malloc(MAX_NUM_TOKENS * sizeof(char *));
char *token = (char *)malloc(MAX_TOKEN_SIZE * sizeof(char));
int i, tokenIndex = 0, tokenNo = 0;
for (i = 0; i < strlen(line); i++) {
char readChar = line[i];
if (readChar == delim) {
token[tokenIndex] = '\0';
if (tokenIndex != 0) {
token = trim(token, ' ');
token = trim(token, '\n');
tokens[tokenNo] = (char *)malloc(MAX_TOKEN_SIZE * sizeof(char));
strcpy(tokens[tokenNo++], token);
tokenIndex = 0;
}
} else {
if (readChar != '\n' && readChar != '\t') {
token[tokenIndex++] = readChar;
}
}
}
if (tokenIndex != 0) {
// This means that we are at the end of the
// string and it has not been copied yet.
token[tokenIndex] = '\0';
token = trim(token, ' ');
token = trim(token, '\n');
tokens[tokenNo] = (char *)malloc(MAX_TOKEN_SIZE * sizeof(char));
strcpy(tokens[tokenNo++], token);
}
// TODO: free(token) gives error here. Need to debug for it.
tokens[tokenNo] = NULL;
return tokens;
}
void destroy_tokens(char **tokens) {
for (int i = 0; tokens[i] != NULL; i++) {
free(tokens[i]);
}
}
char *concat(char *str1, char *str2) {
// strcat using pointers.
char *res = malloc(strlen(str1) + strlen(str2) + 1);
int i = 0, curr_pos = 0;
while (str1[i] != '\0') {
res[curr_pos++] = str1[i++];
}
i = 0;
while (str2[i] != '\0') {
res[curr_pos++] = str2[i++];
}
return res;
}
char *trim(char *str, char ch) {
// This function behaves same as the python/js trim function.
// We don't modifiy the original pointer so that we can later free the memory.
char *t = str;
while (*t == ch) {
t++;
}
for (int i = strlen(t) - 1; t[i] == ch; i--) {
t[i] = '\0';
}
return t;
}
void exit_shell() {
printf("\nClosed all Background processes\n");
exit(0);
}