-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
executable file
·113 lines (102 loc) · 2.84 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
109
110
111
112
113
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: luperez <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/11/26 00:04:04 by luperez #+# #+# */
/* Updated: 2014/11/28 17:09:52 by luperez ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static t_hist *new_historic(int const fd)
{
t_hist *historic;
historic = (t_hist *)malloc(sizeof(t_hist));
if (historic == NULL)
return (NULL);
historic->fd = fd;
historic->garbage = NULL;
historic->start = NULL;
return (historic);
}
static t_str *new_str(void)
{
t_str *str;
str = (t_str *)malloc(sizeof(t_str));
if (str == NULL)
return (NULL);
str->str = NULL;
str->next = NULL;
return (str);
}
static int achievement(t_hist *historic, char **line)
{
size_t len;
int i;
int y;
int z;
if (!historic)
return (-1);
z = 0;
y = -1;
len = ft_s_strlen(historic->start);
*line = (char *)malloc(len + 1);
ft_bzero(*line, len + 1);
while (historic->start)
{
i = -1;
while (historic->start->str[++i])
line[0][++y] = historic->start->str[i];
historic->start = historic->start->next;
z++;
}
return (1);
}
static int loop(t_str *str, t_hist *historic,\
char **line, int success)
{
int i;
while (success && str)
{
i = -1;
while (str->str[++i] && str->str[i] != '\n' && str->str[i] != '\r')
;
if (str->str[i] == '\n' || str->str[i] == '\r')
{
while (str->str[i] == '\n')
str->str[i++] = '\0';
historic->garbage = &str->str[i];
return (achievement(historic, line));
}
str->next = new_str();
str = str->next;
str->str = (char *)malloc(sizeof(char) * BUFF_SIZE + 1);
ft_bzero(str->str, BUFF_SIZE + 1);
success = read(historic->fd, str->str, BUFF_SIZE);
}
return (0);
}
int get_next_line(int const fd, char **line)
{
static t_hist *historic;
t_str *str;
int success;
success = 1;
str = new_str();
if (historic && historic->fd == fd && historic->garbage)
str->str = historic->garbage;
else
{
historic = new_historic(fd);
str->str = (char *)malloc(sizeof(char) * BUFF_SIZE + 1);
ft_bzero(str->str, BUFF_SIZE + 1);
success = read(fd, str->str, BUFF_SIZE);
}
historic->start = str;
if (loop(str, historic, line, success))
return (1);
achievement(historic, line);
return (0);
}