-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.c
100 lines (87 loc) · 1.96 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
#include "headers.h"
// This will be global
// char* commands[20];
// int ptr=0;
// history implemented
void history(int flag_output, char *arg)
{
FILE *fp = fopen("history.txt", "r");
if (fp == NULL)
{
printf("Cannot display history");
}
else
{
char c = fgetc(fp);
int i = 0;
/*----------------STARTED HERE----------------------*/
if (flag_output)
if (ptr < 20)
{
while (c != EOF)
{
printf("%c", c);
c = fgetc(fp);
}
}
else
{
// print only last 10 commands of the file
while (c != EOF)
{
if (i >= ptr - 10)
{
printf("%c", c);
}
if (c == '\n')
{
i++;
}
c = fgetc(fp);
}
}
/*-----------------ENDED-----------------*/
}
fclose(fp);
}
// write commands to history file
void write_history(char *command)
{
FILE *fp;
fp = fopen("history.txt", "w");
if (ptr >= 20)
{
int i;
for (i = 1; i <= 20; i++)
{
if (i == 20)
{
continue;
}
strcpy(commands[i - 1], commands[i]);
}
strcpy(commands[19], command);
// ptr=0;
// overwrite the file from the start
fseek(fp, 0, SEEK_SET);
for (int i = 0; i < 20; i++)
{
fprintf(fp, "%s", commands[i]);
}
ptr = 20;
}
else
{
strcpy(commands[ptr], command);
for (int i = 0; i <= ptr; i++)
{
fprintf(fp, "%s", commands[i]);
}
ptr++;
if (ptr > 20)
{
ptr = 20;
}
}
fclose(fp);
}