-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhistory.c
More file actions
47 lines (46 loc) · 1.06 KB
/
history.c
File metadata and controls
47 lines (46 loc) · 1.06 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
#include "headers.h"
#include "history.h"
void history(char *command, int args, char home[])
{
char file[1000];
strcpy(file, home);
strcat(file, "/hist.txt");
int fd = open(file, O_RDWR | O_CREAT, 0777);
char buffer[1000];
int size = read(fd, buffer, 1000);
buffer[size] = '\0';
int commands = 0;
for (int i = 0; i < size; i++)
{
if (buffer[i] == '\n')
{
commands++;
}
}
if (commands < 20)
{
write(fd, command, strlen(command) - 1);
}
else
{
close(fd);
fd = open(file, O_TRUNC | O_RDWR | O_CREAT, 0777);
lseek(fd, 0, SEEK_SET);
int remove = 0;
for (int i = 0; i < size; i++)
{
if (buffer[i] != '\n')
{
remove++;
}
else
{
break;
}
}
lseek(fd, 0, SEEK_SET);
write(fd, buffer + remove + 1, strlen(buffer) - remove - 1);
write(fd, command, strlen(command) - 1);
}
write(fd, "\n", 1);
}