-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadlinebuf.c
More file actions
84 lines (71 loc) · 1.64 KB
/
readlinebuf.c
File metadata and controls
84 lines (71 loc) · 1.64 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
/**
* A buffered readline implementation. Currently fails if line size exceeds
* defined BUFSZ. Could fix by either dynamically allocating memory,
* or to avoid this, allowing the user to pass buffers into the init func.
*/
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define BUFSZ 128
struct rlbuf {
int fd, eof;
char buf[BUFSZ], res[BUFSZ], *cur, *ep;
};
int readLineBufInit(int fd, struct rlbuf *rlbuf) {
int len;
rlbuf->fd = fd;
if ((len = read(fd, rlbuf->buf, BUFSZ)) == -1)
return -1;
rlbuf->cur = rlbuf->buf;
rlbuf->ep = rlbuf->buf + len;
rlbuf->eof = 0;
return 0;
}
char *readLineBuf(struct rlbuf *rlbuf) {
char *src, *dest;
int len;
if (rlbuf->cur >= rlbuf->ep && rlbuf->eof)
return NULL;
dest = rlbuf->res;
for (;;) {
src = rlbuf->cur;
for(len = 0; rlbuf->cur < rlbuf->ep && *rlbuf->cur != '\n';
rlbuf->cur++, len++)
;
if (dest + len + 1 > rlbuf->res + BUFSZ) {
errno = EFBIG;
return NULL;
}
memcpy(dest, src, len);
dest += len;
if (rlbuf->cur < rlbuf->ep || rlbuf->eof) {
rlbuf->cur++;
*dest = '\0';
return rlbuf->res;
}
// Need to grab more
memset(rlbuf->buf, 0, BUFSZ);
if ((len = read(rlbuf->fd, rlbuf->buf, BUFSZ)) == -1)
return NULL;
if (len != BUFSZ)
rlbuf->eof = 1;
rlbuf->cur = rlbuf->buf;
rlbuf->ep = rlbuf->cur + len;
}
}
#ifdef TEST
int main(int argc, char **argv) {
struct rlbuf rlbuf;
int fd;
char *res;
fd = open(argv[1], O_RDONLY);
readLineBufInit(fd, &rlbuf);
while ((res = readLineBuf(&rlbuf)) != NULL)
printf("LINE: '%s'\n", res);
puts("EOF");
exit(EXIT_SUCCESS);
}
#endif