-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistory.c
103 lines (97 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 "header.h"
#include "historyNode.h"
historyNode *head = NULL, *tail = NULL;
int size = 0;
void updateHistory()
{
// printf("updating");
historyNode *temp = head;
int fd = open("./history.txt", O_WRONLY | O_CREAT);
char *cmdLine;
while (temp != NULL)
{
// printf("%s\n", temp->cmd);
cmdLine = strtok(temp->hisLine, "\n");
strcat(cmdLine, "\n");
write(fd, cmdLine, strlen(cmdLine));
temp = temp->next;
}
}
void pushHisQ(char st[])
{
// printf("%s\n", st);
if (st == NULL)
return;
historyNode *temp = (historyNode *)malloc(sizeof(historyNode));
temp->next = NULL;
temp->prev = NULL;
strcpy(temp->hisLine, st);
size++;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
temp->prev = tail;
tail->next = temp;
tail = temp;
}
while (size > 20)
{
head = head->next;
head->prev = NULL;
size -= 1;
}
updateHistory();
}
void historyInit()
{
FILE *hisFile = fopen("./history.txt", "rw");
char cmd[1000];
if (hisFile == NULL)
{
perror("History File: ");
printf("creating and changing permissions of file\n");
chmod("./history.txt", 0777);
return;
}
char *cmdLine;
while (fgets(cmd, 1000, hisFile) != NULL)
{
cmdLine = strtok(cmd, "\n");
if (cmdLine == NULL)
{
continue;
}
pushHisQ(cmdLine);
}
fclose(hisFile);
updateHistory();
}
int printHis(int numPar, char *par[])
{
if (numPar > 1)
{
perror("history: Too many arguments:");
return -1;
}
int num = 10;
if (numPar == 1)
{
num = atoi(par[0]);
}
if (num > size)
num = size;
historyNode *temp = head;
int i = 0;
while (temp != NULL && i < size)
{
if (size - i <= num)
printf("%s\n", strtok(temp->hisLine, "\n"));
temp = temp->next;
i++;
}
return 1;
}