-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5-7.c
More file actions
129 lines (105 loc) · 1.72 KB
/
5-7.c
File metadata and controls
129 lines (105 loc) · 1.72 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
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
116
117
118
119
120
121
122
123
124
125
126
127
#define NLINES 32
#define LINE 256
#define IN 1
#define BUF 512
int ptc(int);
int pts(char*);
int slen(char*);
int getch(int);
int getln(int, char*, int);
int readlines(int, char**, char*, int);
void printlines(char**, int);
int fopn(char*, int);
void scp(char*,char*);
char *lnp[NLINES];
char buf[BUF];
test()
{
static char buf[LINE];
int fd;
fd = open("f", 0);
while (getln(fd, buf, LINE))
pts(buf);
}
void main()
{
int fd, n;
fd = fopn("f", 0);
n = readlines(fd, lnp, buf, NLINES);
printlines(lnp, n);
}
void printlines(char **lineptr, int nlines)
{
int c;
for (c = 0; c < nlines; c++)
pts(lineptr[c]);
}
void scp(char *in, char *out)
{
int c;
for (c = 0; in[c]; c++)
out[c] = in[c];
}
int readlines(int fd, char **lineptr, char *arr, int maxlines)
{
int nlines, len, i;
static char buf[LINE];
char *p;
p = arr;
nlines = 0;
while ((len = getln(fd, buf, LINE)) && nlines < maxlines) {
if (p + len > arr + BUF)
return nlines; // prevent overflow, but preserve valid lines
scp(buf, p);
lineptr[nlines++] = p;
p = p + len + 1;
}
return nlines;
}
int fopn(char *p, int flag)
{
return open(p, flag);
}
int getln(int fd, char *buf, int lim)
{
int n, c;
n = 0;
while ((c = getch(fd)) && c != '\n' && c < lim - 2)
buf[n++] = c;
if (c == '\n')
buf[n++] = '\n';
buf[n] = 0;
return n;
}
int ptc(int c)
{
int b[1];
b[0] = c;
return write(1, b, 1);
}
int pts(char *s)
{
return write(1, s, slen(s));
}
int slen(char *s)
{
int c;
for (c = 0; s[c++]; )
;
return c;
}
int getch(int fd)
{
static char *sp;
static char *ep;
static char in[IN];
int c;
if (sp == ep) {
for (c = 0; c < IN; c++)
in[c] = 0;
sp = in;
ep = sp + IN;
read(fd, in, IN);
}
return *(sp++);
}