-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line_bonus.c
134 lines (123 loc) · 2.81 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mriant <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/17 11:09:39 by mriant #+# #+# */
/* Updated: 2021/12/17 11:49:46 by mriant ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line_bonus.h"
char *ft_strjoin_free(char *s, char const *s2)
{
char *result;
size_t i;
size_t j;
i = 0;
j = 0;
result = ft_calloc(sizeof(char), (ft_strlen(s) + ft_strlen(s2) + 1));
if (!result)
{
free (s);
return (NULL);
}
while (s && s[i])
{
result[i] = s[i];
i ++;
}
while (s2 && s2[j])
{
result[i] = s2[j];
i ++;
j ++;
}
free(s);
return (result);
}
long int ft_readline(int fd, char **buf, char **line)
{
long int ret;
if (!(*buf))
return (-1);
ret = 1;
while (ret > 0 && !ft_strchr(line[0], '\n'))
{
ret = read (fd, buf[0], BUFFER_SIZE);
buf[0][ret] = '\0';
line[0] = ft_strjoin_free(line[0], buf[0]);
}
return (ret);
}
void ft_setline(char **line, char **tail)
{
char *endline;
endline = ft_strchr(line[0], '\n');
free(*tail);
if (endline)
{
*tail = ft_strdup(endline + 1);
endline[1] = '\0';
}
else
*tail = NULL;
}
void ft_clean(char *buf, char *tail, char *line)
{
free(buf);
free(tail);
free(line);
}
char *get_next_line(int fd)
{
long int ret;
char *buf;
static char *tail[256];
char *line;
if (fd < 0 || fd >= 256 || BUFFER_SIZE <= 0)
return (NULL);
buf = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
tail[fd] = ft_strjoin_free(tail[fd], "\0");
line = ft_strdup(tail[fd]);
ret = ft_readline(fd, &buf, &line);
if (ret < 0 || !buf)
{
ft_clean(buf, tail[fd], line);
return (NULL);
}
ft_setline(&line, &tail[fd]);
if (ret == 0 && !tail[fd] && line[0] == '\0')
{
free(line);
line = NULL;
}
free(buf);
return (line);
}
/*
int main(void)
{
int fd1;
int fd2;
fd1 = open("test_file", O_RDONLY);
fd2 = open("test_file_2", O_RDONLY);
char *str = get_next_line(fd1);
printf("fd1 :%s", str);
free(str);
while (str)
{
str = get_next_line(0);
printf("input : %s", str);
free(str);
str = get_next_line(fd2);
printf("fd2 : %s", str);
free(str);
str = get_next_line(fd1);
printf("fd1 : %s", str);
free (str);
}
close (fd1);
close (fd2);
}*/