-
Notifications
You must be signed in to change notification settings - Fork 0
/
history_handler.c
72 lines (61 loc) · 1.57 KB
/
history_handler.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
61
62
63
64
65
66
67
68
69
70
71
72
#include "headers.h"
#include "history_handler.h"
#include "util.h"
// read lines
// if read line is not equal to last read then
// get last 20 lines if possible
// write the last 20 lines
#define history_file "/tmp/.shell_history"
void add_history(char tokens[]) {
if (strcmp(tokens, "") == 0) return;;
FILE *f;
f = fopen(history_file, "a");
fclose(f);
f = fopen(history_file, "r");
char *lines[100];
int n = 0;
if (f != NULL) {
lines[n] = malloc(size_buff);
size_t s = size_buff;
while (getline(&lines[n], &s, f) != -1) {
if (strcmp(lines[n], "\n") != 0)
lines[++n] = malloc(size_buff);
}
}
fclose(f);
f = fopen(history_file, "w");
int i;
for ( i = max(0, n - 20); i < n; i++) {
fprintf(f, "%s", lines[i]);
}
char new[size_buff];
sprintf(new, "%s\n", tokens);
if(i == 0 || strcmp(new, lines[i - 1]) != 0){
fprintf(f, "%s", new);
}
fclose(f);
for(i = 0; i <= n; i++) {
free(lines[i]);
}
}
void show_history(int no) {
FILE *f;
f = fopen(history_file, "a");
fclose(f);
f = fopen(history_file, "r");
char *lines[100];
int n = 0;
if (f != NULL) {
lines[n] = malloc(size_buff);
size_t s = size_buff;
while (getline(&lines[n], &s, f) != -1) {
if (strcmp(lines[n], "\n") != 0)
lines[++n] = malloc(size_buff);
}
}
fclose(f);
for (int i = max(0, n - no); i < n; i++) {
printf("%s\n", lines[i]);
free(lines[i]);
}
}