Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yabtaour
GitHub Repository: yabtaour/Get_next_line-42
Path: blob/main/get_next_line.c
342 views
1
/* ************************************************************************** */
2
/* */
3
/* ::: :::::::: */
4
/* get_next_line.c :+: :+: :+: */
5
/* +:+ +:+ +:+ */
6
/* By: yabtaour <[email protected]> +#+ +:+ +#+ */
7
/* +#+#+#+#+#+ +#+ */
8
/* Created: 2021/12/07 11:22:05 by yabtaour #+# #+# */
9
/* Updated: 2021/12/07 20:10:14 by yabtaour ### ########.fr */
10
/* */
11
/* ************************************************************************** */
12
#include "get_next_line.h"
13
14
char *ft_read(int fd, char *str)
15
{
16
char *line;
17
int len;
18
19
line = malloc(1 + BUFFER_SIZE);
20
if (!line)
21
return (NULL);
22
len = 1;
23
while (!ft_strchr(str, '\n') && len)
24
{
25
len = read(fd, line, BUFFER_SIZE);
26
if (len == -1)
27
{
28
free(line);
29
return (NULL);
30
}
31
line[len] = '\0';
32
str = ft_strjoin(str, line);
33
}
34
free(line);
35
return (str);
36
}
37
38
char *ft_get_line(char *str)
39
{
40
char *line;
41
int i;
42
43
i = 0;
44
if (!str[0])
45
return (NULL);
46
while (str[i] != '\0' && str[i] != '\n')
47
i++;
48
line = malloc(i + 2);
49
if (!line)
50
return (NULL);
51
i = 0;
52
while (str[i] != '\0' && str[i] != '\n')
53
{
54
line[i] = str[i];
55
i++;
56
}
57
if (str[i] == '\n')
58
line[i++] = '\n';
59
line[i] = '\0';
60
return (line);
61
}
62
63
char *ft_get_rest(char *str)
64
{
65
char *line;
66
int i;
67
int j;
68
int len;
69
70
i = 0;
71
while (str[i] != '\0' && str[i] != '\n')
72
i++;
73
if (!str[i])
74
{
75
free(str);
76
return (NULL);
77
}
78
len = ft_strlen(&str[i + 1]);
79
line = (char *)malloc(sizeof(char) * (len + 1));
80
if (!line)
81
return (NULL);
82
j = 0;
83
i++;
84
while (str[i] != '\0')
85
line[j++] = str[i++];
86
line[j] = '\0';
87
free(str);
88
return (line);
89
}
90
91
char *get_next_line(int fd)
92
{
93
static char *current_line;
94
char *line;
95
96
if (fd < 0 || BUFFER_SIZE <= 0)
97
return (NULL);
98
current_line = ft_read(fd, current_line);
99
if (!current_line)
100
return (NULL);
101
line = ft_get_line(current_line);
102
current_line = ft_get_rest(current_line);
103
return (line);
104
}
105
106