-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.c
60 lines (55 loc) · 1.65 KB
/
history.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
#include "history.h"
void openHistory(){
char *homedir = getenv("HOME");
int i;
for (i = 0; i < PATH_MAX; i++){
catshDirectory[i] = '\0';
}
strcat(catshDirectory, homedir);
strcat(catshDirectory, "/.catsh_history");
historyFile = open(catshDirectory, O_RDWR | O_APPEND | O_CREAT, 0777);
}
void writeCommandToHistory(char* command){
openHistory();
write(historyFile, command, strlen(command) * sizeof(char));
}
void readHistory(){
openHistory();
struct stat fileInfo;
stat(catshDirectory, &fileInfo);
int fileSize = fileInfo.st_size;
char *historyFileContents = malloc(fileSize + sizeof(char));
read(historyFile, historyFileContents, fileSize + sizeof(char));
historyLength = countDelimiters(historyFileContents, '\n') - 1;
history = parse_args(historyFileContents, '\n');
}
void printHistory(){
int i;
readHistory();
if (historyLength - 1){
printf("History of commands used: \n");
for (i = 0; i < historyLength - 1; i++)
{
printf("%d: %s\n", i, history[i]);
}
}else{
printf("No commands in history.\n");
}
}
void runHistory(char *input){
int indice;
sscanf(input, "%d", &indice);
if (history == NULL)
{
readHistory();
}
if (indice >= 0 && indice < historyLength){
printf("%s\n", history[indice]);
executeLine(history[indice]);
}else if (indice < 0 && indice * -1 < historyLength){
printf("%s\n", history[historyLength - 1 + indice]);
executeLine(history[historyLength - 1 + indice]);
}else{
printf("Invalid history indice given. Please try again.");
}
}