-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathgetln.c
69 lines (61 loc) · 1.23 KB
/
getln.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
/*
20140323
20241207 - reformated using clang-format
Jan Mojzis
Public domain.
*/
#include <poll.h>
#include <unistd.h>
#include "e.h"
#include "getln.h"
static int getch(int fd, char *x) {
int r;
struct pollfd p;
for (;;) {
r = read(fd, x, 1);
if (r == -1) {
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
p.fd = fd;
p.events = POLLIN | POLLERR;
poll(&p, 1, -1);
continue;
}
}
break;
}
return r;
}
/*
The function 'getln' reads line from filedescriptor 'fd' into
buffer 'xv' of length 'xmax'.
*/
int getln(int fd, void *xv, long long xmax) {
long long xlen;
int r;
char ch;
char *x = (char *) xv;
if (xmax < 1) {
errno = EINVAL;
return -1;
}
x[0] = 0;
if (fd < 0) {
errno = EBADF;
return -1;
}
xlen = 0;
for (;;) {
if (xlen >= xmax - 1) {
x[xmax - 1] = 0;
errno = ENOMEM;
return -1;
}
r = getch(fd, &ch);
if (r != 1) break;
if (ch == 0) ch = '\n';
x[xlen++] = ch;
if (ch == '\n') break;
}
x[xlen] = 0;
return r;
}