-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line_bonus.c
87 lines (80 loc) · 2.26 KB
/
get_next_line_bonus.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tpierre <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/15 15:17:19 by tpierre #+# #+# */
/* Updated: 2020/03/02 15:50:03 by tpierre ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_strchr(const char *s, int c)
{
while (*s)
{
if (*s == c)
return (char *)(s);
s++;
}
if (*s == c)
return (char *)(s);
return (NULL);
}
int ft_exitprogram(char **data, char **bufforline)
{
free(*data);
free(*bufforline);
return (-1);
}
int ft_copy(char **data, char **line)
{
char *tmp;
int i;
if (ft_strchr(*data, '\n'))
{
i = 0;
while ((*data)[i] != '\n')
i++;
if ((*line = ft_substr(*data, 0, i)) == NULL
|| (tmp = ft_strdup(*data + i + 1)) == NULL)
return (ft_exitprogram(data, line));
free(*data);
*data = tmp;
return (1);
}
else
{
if ((*line = ft_strdup(*data)) == NULL)
return (ft_exitprogram(data, NULL));
free(*data);
*data = NULL;
return (0);
}
}
int get_next_line(int fd, char **line)
{
static char *data[9999];
int len;
char *buff;
char *tmp;
if (!(buff = malloc(sizeof(char) * (BUFFER_SIZE + 1))))
return (-1);
if (fd < 0 || line == NULL || BUFFER_SIZE < 1 || read(fd, buff, 0) < 0)
return (-1);
if (data[fd] == NULL)
if ((data[fd] = ft_strdup("")) == NULL)
return (ft_exitprogram(NULL, &buff));
while (!(ft_strchr(data[fd], '\n'))
&& (len = read(fd, buff, BUFFER_SIZE)) > 0)
{
buff[len] = '\0';
if ((tmp = ft_strjoin(data[fd], buff)) == NULL)
return (ft_exitprogram(&data[fd], &buff));
free(data[fd]);
data[fd] = tmp;
}
free(buff);
return (ft_copy(&data[fd], line));
}