-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
114 lines (104 loc) · 2.68 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
114
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tvandivi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/22 13:21:39 by tvandivi #+# #+# */
/* Updated: 2019/04/05 17:33:20 by tvandivi ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int null_check(char **line, char **tab)
{
if (ft_strlen(*tab) > 0)
{
ft_memdel((void **)line);
free(*line);
*line = ft_strdup(*tab);
ft_bzero(*tab, ft_strlen(*tab));
return (1);
}
return (0);
}
int read_next_buffer(int a, char **tab, char **line, char *buf)
{
int j;
j = 0;
buf[a] = '\0';
while (buf[j] != '\n' && j < (a - 1))
j++;
if (buf[j] == '\n')
{
buf[j] = '\0';
ft_memdel((void **)line);
*line = ft_strjoin(*tab, buf);
ft_bzero(*tab, ft_strlen(*tab));
free(*tab);
if (j >= (a - 1))
*tab = ft_strdup("");
else
*tab = ft_strdup(buf + (j + 1));
free(buf);
return (1);
}
return (0);
}
int chomp_line(char **tab, char **line)
{
char *tmp;
char *ptr;
if (!((ft_strchr(*tab, '\n')) == NULL))
{
ft_memdel((void **)line);
tmp = ft_strchr(*tab, '\n');
*tmp = '\0';
free(*line);
*line = ft_strdup(*tab);
tmp++;
ft_bzero(*tab, ft_strlen(*tab));
ptr = ft_strdup(*tab);
*tab = ft_strjoin(ptr, tmp);
free(ptr);
return (1);
}
return (0);
}
void set_and_free(char **tab, char **buf)
{
char *ptr;
ptr = ft_strdup(*tab);
free(*tab);
*tab = ft_strjoin(ptr, *buf);
free(ptr);
ft_memset(*buf, '\0', BUFF_SIZE);
free(*buf);
*buf = ft_strnew(BUFF_SIZE + 1);
}
int get_next_line(int fd, char **line)
{
static char *tab[OPEN_MAX];
char *buf;
int a;
if (fd < 0 || !(line) || fd > OPEN_MAX || read(fd, &buf, 0) == -1)
return (-1);
if (!(tab[fd]))
tab[fd] = ft_strdup("");
buf = ft_strnew(BUFF_SIZE + 1);
if (ft_strlen(tab[fd]) > 0)
if (chomp_line(&tab[fd], line) == 1)
return (1);
while ((a = read(fd, buf, BUFF_SIZE)) >= 0)
{
if (a == 0)
{
free(buf);
return (null_check(line, &tab[fd]));
}
if ((read_next_buffer(a, &tab[fd], line, buf)) == 1)
return (1);
set_and_free(&tab[fd], &buf);
}
return (-1);
}