-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.c
103 lines (89 loc) · 2.02 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
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
96
97
98
99
100
101
102
103
#include <dirent.h>
#include <fcntl.h>
#include <readline/history.h>
#include <readline/readline.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <unistd.h>
#include "main.h"
int cnt = 0;
void push(char *in, char **qu) {
qu[cnt] = in;
cnt++;
}
void history(char *rd) {
cnt = 0;
char **qu = (char **)malloc(sizeof(char *) * 500);
char st[100] = " ";
strcpy(st, home_dir);
strcat(st, "/");
strcat(st, "his.txt");
int fd = open(st, O_RDWR | O_CREAT, 0677);
char *buff = (char *)(calloc(1000, 1));
read(fd, buff, 1000);
char **parts = (char **)malloc(50 * sizeof(char *));
parts[0] = strtok(buff, "\n");
if (parts[0] != NULL) {
push(parts[0], qu);
}
int i = 0;
while (parts[i] != NULL) {
++i;
parts[i] = strtok(NULL, "\n");
if (parts[i] != NULL) {
push(parts[i], qu);
}
}
--i;
if (parts[0] != NULL) {
if (strcmp(parts[i], rd) != 0) {
push(rd, qu);
}
} else {
push(rd, qu);
}
close(fd);
fd = open(st, O_WRONLY | O_TRUNC, 0677);
int p = 0;
if (cnt - 20 > 0) {
p = cnt - 20;
}
for (int i = p; i < cnt; i++) {
write(fd, qu[i], strlen(qu[i]));
if (i < cnt - 1) {
write(fd, "\n", 1);
}
}
close(fd);
}
void showhistory() {
char **qu = (char **)malloc(500);
char *st = (char *)malloc(1000);
strcpy(st, home_dir);
strcat(st, "/");
strcat(st, "his.txt");
int fd = open(st, O_RDONLY);
char *buff = (char *)malloc(4000);
read(fd, buff, 1000);
char *ptr = strtok(buff, "\n");
cnt = 0;
if (ptr) {
qu[cnt++] = ptr;
while ((ptr = strtok(NULL, "\n"))) {
qu[cnt++] = ptr;
}
}
close(fd);
int p = 0;
if (cnt > 10) {
p = cnt - 10;
}
for (int i = p; i < cnt; i++) {
printf("%s\n", qu[i]);
}
}