-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistory_func2.c
79 lines (74 loc) · 1.9 KB
/
history_func2.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
#include "shell.h"
/**
* add_cmdhist - add new command to the history linked list
* @history: history linked list
* @cmd: command to put into the history
* Description: Adds the new command to the end of the linked
* list, keeps count on how many entries there are in the list,
* if the list execeeds, 4096, then the head will pop off
*/
void add_cmdhist(hist_t *history, char *cmd)
{
static int hist_index = 1;
int i, len;
hist_t *temp;
char *new_cmd;
new_cmd = safe_malloc(sizeof(char) * _strlen(cmd) + 1);
temp = history;
if (hist_index == 1)
for (temp = history; temp != NULL; temp = temp->next)
hist_index++;
len = _strlen(cmd);
for (i = 0; i < len - 1; i++)
new_cmd[i] = cmd[i];
new_cmd[i] = '\0';
if (len > 1)
add_history(history, new_cmd);
hist_index++;
_free(new_cmd);
}
/**
* write_history - writing the history linked list to the file:
* .simple_shell_history
* @envp: environemental variable linked list to find the path of file
* @history: history link list to find what to write in
* Return: 0 if success and 1 if failed to find path for file
*/
int write_history(env_t *envp, hist_t *history)
{
hist_t *temp, *temp_c;
char *path;
int fd, count;
count = 0;
history = history->next;
for (temp_c = history; temp_c != NULL; temp_c = temp_c->next)
count++;
if (count > 4096)
{
count = count - 4096;
while (count > 0)
{
history = history->next;
count--;
}
}
path = safe_malloc(sizeof(char) * BUFSIZE);
_memset(path, '\0', BUFSIZE);
path = rm_vname(envp, "HOME=", BUFSIZE);
if (path == NULL)
{
_write("Error: failed to find history file\n");
_write("Cannot write history\n");
return (1);
}
_strcat(path, "/.simple_shell_history");
fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0600);
for (temp = history; temp != NULL; temp = temp->next)
{
write(fd, temp->cmd, _strlen(temp->cmd));
write(fd, "\n", 1);
}
_free(history);
close(fd);
return (0);
}