-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
69 lines (62 loc) · 1.34 KB
/
get_next_line.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
#include "get_next_line.h"
static int exit_with_error(char **line, char **result)
{
free(*result);
*result = NULL;
*line = NULL;
return (-1);
}
static int get_line(char **line, char **result, char *n_ptr)
{
char *tmp_str;
if (n_ptr)
{
*line = ft_substr(*result, 0, n_ptr - *result);
tmp_str = ft_substr(*result, n_ptr - *result + 1,
ft_strlen(*result) - (n_ptr - *result));
free(*result);
*result = tmp_str;
return (1);
}
else if (!ft_strlen(*result))
*line = ft_strdup(NULL);
else
*line = ft_strdup(*result);
free(*result);
*result = NULL;
return (0);
}
static int gnl_handler(int fd, char **line, char *buffer)
{
int read_bytes;
char *n_ptr;
static char *result = NULL;
if (!result)
result = ft_strdup(NULL);
while (1)
{
read_bytes = read(fd, buffer, BUFFER_SIZE);
if (read_bytes < 0)
return (exit_with_error(line, &result));
buffer[read_bytes] = '\0';
if (append_str(&result, buffer))
return (exit_with_error(line, &result));
n_ptr = ft_strchr(result, '\n');
if (n_ptr || !read_bytes)
return (get_line(line, &result, n_ptr));
}
return (1);
}
int get_next_line(int fd, char **line)
{
int val;
char *buffer;
if (fd < 0 || BUFFER_SIZE <= 0)
return (-1);
buffer = (char *)malloc(BUFFER_SIZE + 1);
if (!buffer)
return (-1);
val = gnl_handler(fd, line, buffer);
free(buffer);
return (val);
}