-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhistory.c
More file actions
95 lines (73 loc) · 2.11 KB
/
history.c
File metadata and controls
95 lines (73 loc) · 2.11 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
#include "headers.h"
int hist_limit = 20;
void read_history(){
char path[2000]="";
strcpy(path, home);
strcat(path, "/history.txt");
char *command = NULL;
size_t len;
FILE *file_ptr = NULL;
file_ptr = fopen(path, "r");
if(fopen(path, "r") == NULL){
printf("\033[0;31mError: history.txt not found\033[0m\n");
perror("fopen");
}
// for(int i=0; i<hist_limit; i++){
// getline(&command, &len, file_ptr);
// strcpy(hist[i], command);
// printf("%d %s\n", i, hist[i]);
// }
int i=0;
while(getline(&command, &len, file_ptr) != -1){
strcpy(hist[i++], command);
}
// for(int i=0; i<hist_limit; i++){
// printf("%d: ", i);
// printf("%s\n", hist[i]);
// }
fclose(file_ptr);
}
void write_history(){
char path[2000]="";
strcpy(path, home);
strcat(path, "/history.txt");
FILE *file_ptr = NULL;
file_ptr = fopen(path, "w");
if(file_ptr == NULL){
printf("\033[0;31mError: history.txt not found\033[0m\n");
perror("fopen");
}
for(int i=0; i<hist_limit; i++){
fprintf(file_ptr, "%s", hist[i]);
}
fclose(file_ptr);
}
void update_history(char *command){
for(int i=1; i<hist_limit; i++){
strcpy(hist[i-1], hist[i]);
}
strcpy(hist[hist_limit-1],command);
// for(int i=0; i<hist_limit; i++){
// printf("%s\n", hist[i]);
// }
write_history();
}
void history(char *command[], ll n){
int n_cmds; /* history n "text" */
if(n>2){
printf("\033[0;31mError: Too many arguments\033[0m\n");
return;
}
else if(n==1){ /* history n */
n_cmds = 10;
}
else{
n_cmds = atoi(command[1]); /* history [n>20] */
if(n_cmds > hist_limit){
n_cmds = hist_limit;
}
}
for(int i=hist_limit-n_cmds; i<hist_limit; i++){
printf("%s", hist[i]);
}
}