-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadline.c
54 lines (54 loc) · 969 Bytes
/
readline.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
/*--- readline.c -> read a text line from a descriptor, one byte at a time ---*/
#include "meow.h"
static int read_cnt;
static char *read_ptr;
static char read_buf[MAXLINE];
static ssize_t my_read(int fd, char *ptr)
{
if(read_cnt <= 0)
{
meow:
if((read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0)
{
if(errno == EINTR)
goto meow;
return(-1);
}
else if(read_cnt == 0)
return(0);
read_ptr = read_buf;
}
read_cnt--;
*ptr = *read_ptr++;
return(1);
}
ssize_t readline(int fd, void *vptr, size_t maxlen)
{
ssize_t n, rc;
char c, *ptr;
ptr = vptr;
for(n=1;n<maxlen;n++)
{
if((rc=my_read(fd,&c)) == 1)
{
*ptr++ = c;
if(c == '\n')
break; /*newline is stored */
}
else if(rc == 0)
{
*ptr = 0;
return(n - 1); /* n-1 bytes were read */
}
else
return(-1); /*error*/
}
*ptr = 0; /* null terminate */
return(n);
}
ssize_t readlinebuf(void **vptrptr)
{
if(read_cnt)
*vptrptr = read_ptr;
return(read_cnt);
}