-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.c
More file actions
93 lines (82 loc) · 2.19 KB
/
Main.c
File metadata and controls
93 lines (82 loc) · 2.19 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "List.h"
#include "DisplayFiles.h"
int main() {
char input[256];
char **args = malloc(10 * sizeof(char *));
if (!args) {
perror("malloc failed");
exit(EXIT_FAILURE);
}
char *cwd = getcwd(NULL, 0);
if (cwd == NULL) {
perror("getcwd failed");
exit(EXIT_FAILURE);
}
while (1) {
char prompt[512];
snprintf(prompt, sizeof(prompt), "%s </> ", cwd);
char *input = readline(prompt);
if (input == NULL) {
break;
}
if (strlen(input) > 0) {
add_history(input);
}
input[strcspn(input, "\n")] = '\0';
int i = 0;
args[i] = strtok(input, " ");
while (args[i] != NULL) {
i++;
if (i >= 10) {
args = realloc(args, (i + 1) * sizeof(char *));
if (!args) {
perror("realloc failed");
exit(EXIT_FAILURE);
}
}
args[i] = strtok(NULL, " ");
}
if (args[0] == NULL) {
continue;
}
if (strcmp(args[0], "ls") == 0) {
list_directories(cwd);
}
else if (strcmp(args[0], "cd") == 0) {
if (args[1] != NULL) {
if (chdir(args[1]) == 0) {
cwd = getcwd(NULL, 0);
} else {
perror("cd failed");
}
} else {
printf("Usage: cd <directory>\n");
}
}
else if (strcmp(args[0], "cat") == 0) {
if (args[1] != NULL) {
cat_command(args[1]);
} else {
printf("Usage: cat <filename>\n");
}
}
else if (strcmp(args[0], "clear") == 0) {
system("clear");
}
else if (strcmp(args[0], "exit") == 0) {
break;
}
else {
printf("%s: command not found\n", args[0]);
}
}
free(args);
free(cwd);
return 0;
}