-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistory.c
115 lines (97 loc) · 1.67 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
104
105
106
107
108
109
110
111
112
113
114
115
#include "shell.h"
#include "history.h"
/**
* gethistory - gets the history list
* Return: 0 uposon success
*/
HistList **gethistory()
{
static HistList *hlist;
return (&hlist);
}
/**
* sethist - set hist and value
* @cmd: command
* Return: 0 upon success
*/
int sethist(char *cmd)
{
HistList **hlistroot = gethistory();
HistList *hlist = *hlistroot;
HistList *ptr = hlist, *new;
if (hlist == NULL)
{
new = malloc(sizeof(HistList));
if (new == NULL)
return (-1);
new->cmd = _strdup(cmd);
new->next = NULL;
*hlistroot = new;
return (0);
}
while (ptr->next != NULL)
ptr = ptr->next;
new = malloc(sizeof(HistList));
if (new == NULL)
return (-1);
new->cmd = _strdup(cmd);
new->next = NULL;
ptr->next = new;
return (0);
}
/**
* print_hist - prints all elements of listint
*
* Return: num of elements
*/
int print_hist(void)
{
HistList **hlistroot = gethistory();
HistList *h = *hlistroot;
int i;
int len, numlen;
char *s, *num;
i = 0;
while (h != NULL)
{
len = _strlen(h->cmd);
s = h->cmd;
num = itos(i);
numlen = _strlen(num);
write(1, num, numlen);
_putchar(' ');
write(1, s, len);
h = h->next;
i++;
}
return (i);
}
/**
* exit_hist - exit history and copy to file
* Return: int
*/
int exit_hist(void)
{
int fd;
char *file = ".simple_shell_history";
int len;
char *s;
HistList **hlistroot = gethistory();
HistList *hlist = *hlistroot;
HistList *ptr = hlist;
fd = open(file, O_CREAT | O_RDWR, 0600);
if (fd == -1)
return (-1);
while (hlist != NULL)
{
ptr = hlist->next;
s = hlist->cmd;
len = _strlen(s);
write(fd, s, len);
free(hlist->cmd);
free(hlist);
hlist = ptr;
}
close(fd);
return (1);
}