-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
111 lines (102 loc) · 2.22 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akdemir <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/07/27 16:39:14 by akdemir #+# #+# */
/* Updated: 2023/08/02 16:58:46 by akdemir ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_read(char *str, int fd)
{
char *tmp;
int byt;
tmp = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
byt = 1;
while (!nlcheck(str) && byt != 0)
{
byt = read(fd, tmp, BUFFER_SIZE);
if (byt == -1)
{
if (str)
free(str);
free(tmp);
return (NULL);
}
tmp[byt] = '\0';
str = ft_strjoin(str, tmp);
}
free(tmp);
return (str);
}
char *ft_getline(char *s)
{
int i;
char *arr;
i = -1;
while (s[++i])
if (s[i] == '\n')
break ;
if (s[i] == '\n')
i++;
arr = (char *)malloc(sizeof(char) * (i + 1));
if (!arr)
return (NULL);
i = 0;
while (s[i] && s[i] != '\n')
{
arr[i] = s[i];
i++;
}
if (s[i] == '\n')
{
arr[i] = s[i];
i++;
}
arr[i] = '\0';
return (arr);
}
char *ft_cutline(char *str)
{
char *cline;
int start;
int len;
int i;
i = -1;
while (str[++i])
if (str[i] == '\n')
break ;
if (str[i] == '\n')
i++;
start = i;
len = (ft_strlen(str) - start);
if (len == 0)
{
free(str);
return (NULL);
}
cline = ft_substr(str, start, len);
free (str);
return (cline);
}
char *get_next_line(int fd)
{
static char *str = NULL;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
str = ft_read(str, fd);
if (!str || !*str)
{
if (str)
free(str);
str = NULL;
return (NULL);
}
line = ft_getline(str);
str = ft_cutline(str);
return (line);
}