-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistory.c
113 lines (91 loc) · 2.27 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
#include "headers.h"
int add_history(char* command, char* starting_working_directory){
char path[1000];
strcpy(path,starting_working_directory);
strcat(path, "/history_tush.txt");
int f_read = open(path, O_RDWR | O_CREAT, 0600);
if(f_read<0){
perror("history");
return 1;
}
long long int size = lseek(f_read, 0, SEEK_END);
lseek(f_read, 0, SEEK_SET);
if(size<0){
perror("r1");
return 1;
}
char contents[size+5];
read(f_read, contents, size);
int lines = 0;
for(int i=0;i<size;i++){
if(contents[i]=='\n'){
lines++;
}
}
// lines++;
if(lines<20){
lseek(f_read, 0, SEEK_END);
int size2 = strlen(command);
write (f_read, command, size2);
write(f_read,"\n",1);
close(f_read);
}
else{
close(f_read);
int f_read = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600);
// printf("mor\n");
int index =0;
while(contents[index]!='\n'){
index++;
}
index++;
size -= index;
write (f_read, contents + index, size);
int size2 = strlen(command);
write (f_read, command, size2);
write(f_read,"\n",1);
close(f_read);
}
return 0;
}
int print_history( int n,char* starting_working_directory){
char path[1000];
strcpy(path,starting_working_directory);
strcat(path, "/history_tush.txt");
int f_read = open(path, O_RDWR | O_CREAT, 0600);
if(f_read<0){
perror("history");
return 1;
}
long long int size = lseek(f_read, 0, SEEK_END);
lseek(f_read, 0, SEEK_SET);
if(size<0){
perror("r1");
return 1;
}
char contents[size+5];
read(f_read, contents, size);
int lines = 0;
for(int i=0;i<size;i++){
if(contents[i]=='\n'){
lines++;
}
}
contents[size] = '\0';
if(lines<=n){
printf("%s",contents);
}
else{
int skip = lines-n;
int index = 0;
for(int i=0;i<skip;i++){
while(contents[index]!='\n'){
index++;
}
index++;
}
printf("%s",contents+index);
}
close(f_read);
return 0;
}