-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
108 lines (99 loc) · 2.51 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: juchoi <juchoi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/26 14:38:56 by juchoi #+# #+# */
/* Updated: 2021/02/15 14:16:21 by juchoi ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_strchr(const char *s, int c)
{
char *str;
str = (char *)s;
while (*str)
{
if (*str == (char)c)
return (str);
str++;
}
if ((char)c == '\0')
return (str);
return (0);
}
static int split_store(char **line, char **store, char *store_point,
char *buf)
{
char *tmp;
if (buf)
{
free(buf);
buf = 0;
}
*store_point = '\0';
if (!(*line = ft_strdup(*store)))
return (-1);
store_point++;
if (*store_point == '\0')
{
free(*store);
*store = 0;
return (1);
}
if (!(tmp = ft_strdup(store_point)))
return (-1);
free(*store);
*store = tmp;
return (1);
}
static int end_line(char **line, char **store, char *buf, int read_len)
{
char *store_point;
if (buf)
{
free(buf);
buf = 0;
}
if (read_len < 0)
return (-1);
if (*store && (store_point = ft_strchr(*store, '\n')))
return (split_store(line, store, store_point, buf));
if (*store)
{
*line = *store;
*store = 0;
return (0);
}
if (!(*line = ft_strdup("")))
return (-1);
return (0);
}
int get_next_line(int fd, char **line)
{
static char *store[OPEN_MAX];
char *store_point;
char *buf;
char *tmp;
int read_len;
if (fd < 0 || !line || BUFFER_SIZE <= 0 || fd > OPEN_MAX)
return (-1);
if (!(buf = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1))))
return (-1);
while ((read_len = read(fd, buf, BUFFER_SIZE)) > 0)
{
buf[read_len] = '\0';
tmp = store[fd];
store[fd] = ft_strjoin(store[fd], buf);
if (tmp)
{
free(tmp);
tmp = 0;
}
if ((store_point = ft_strchr(store[fd], '\n')))
return (split_store(line, &store[fd], store_point, buf));
}
return (end_line(line, &store[fd], buf, read_len));
}