-
Notifications
You must be signed in to change notification settings - Fork 0
/
_fgetline.c
45 lines (41 loc) · 899 Bytes
/
_fgetline.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
#include "main.h"
/**
* _fgetline - reads an entire line from file descriptor
* @lineptr: pointer to the buffer containing the read bytes
* @fd: file descriptor to read from
* Return: number of characters read including the delimiting character
* but not including the terminating null byte
*/
ssize_t _fgetline(char **lineptr, int fd)
{
int count = 0, size = 100;
char *tmp, *buf, *c = malloc(sizeof(char));
if (!lineptr || !c)
return (-1);
if (!(*lineptr))
{
tmp = realloc((*lineptr), (sizeof(char) * size));
if (!tmp)
return (-1);
*lineptr = tmp;
}
buf = *lineptr;
while (read(fd, c, 1) > 0)
{
buf[count++] = *c;
if (count >= size)
{
size *= 2;
tmp = realloc((*lineptr), (sizeof(char) * size));
if (!tmp)
return (-1);
*lineptr = tmp;
}
buf = *lineptr;
if (*c == '\n')
break;
}
buf[count++] = '\0';
free(c);
return (count);
}