-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshell.c
More file actions
93 lines (73 loc) · 2.1 KB
/
Copy pathshell.c
File metadata and controls
93 lines (73 loc) · 2.1 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
// Muhammad Huzaifa Elahi
// 260726386
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "shell.h"
#include "interpreter.h"
// Constants
const int SHELL_LENGTH = 1000;
const int MAX_WORD_COUNT = 100;
const int MAX_WORD_LENGTH = 100;
int main(){
char *shellBuffer = calloc(SHELL_LENGTH, sizeof(char));
int errCode = 0;
printf("Welcome to the Muhammad Huzaifa Elahi shell!\n");
printf("Version 1.0 Created January 2020\n");
while(1){
printf("$ ");
if(fgets(shellBuffer, SHELL_LENGTH, stdin) == NULL){
printf("Unable to retrieve process input, please try again\n");
return 0;;
}
while(shellBuffer[strlen(shellBuffer)-1] == '\r' || shellBuffer[strlen(shellBuffer)-1] == '\n'){
shellBuffer[strlen(shellBuffer)-1] = '\0';
}
errCode = parse(shellBuffer);
switch(errCode){
case 0:
// No error, continue
break;
case 2:
// Terminate shell (quit)
free(shellBuffer);
return 0;
default:
// continue
break;
}
}
free(shellBuffer);
return 0;
}
int parse(char string[]){
if(string == NULL || strlen(string) == 0){
printf("Please enter a valid command\n");
return -1;
}
char *temp = calloc(MAX_WORD_LENGTH, sizeof(char));
char **words = calloc(MAX_WORD_COUNT, sizeof(char*));
int inputIndex, tokenIndex;
int wordIndex = 0;
for(inputIndex = 0; string[inputIndex]== ' ' && inputIndex < SHELL_LENGTH; inputIndex++); // Skip white spaces
// Move forward while input has not terminated
while(string[inputIndex] != '\0' && inputIndex < SHELL_LENGTH){
// Copy token from input
for(tokenIndex = 0; string[inputIndex] != '\0' && string[inputIndex] != ' ' && inputIndex < SHELL_LENGTH; inputIndex++, tokenIndex++){
temp[tokenIndex] = string[inputIndex]; // Extract a word
}
// Add string terminator to token and add token to word array
words[wordIndex] = calloc(MAX_WORD_LENGTH, sizeof(char));
temp[tokenIndex] = '\0';
words[wordIndex] = strdup(temp);
inputIndex++;
wordIndex++;
}
int errCode = interpreter(words);
for (int i = 0; i < MAX_WORD_COUNT; i++ ){
free(words[i]);
}
free(temp);
free(words);
return errCode;
}