-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
108 lines (99 loc) · 2.71 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: skunert <skunert@student.42heilbronn.de +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/25 18:40:12 by skunert #+# #+# */
/* Updated: 2023/04/03 16:02:25 by skunert ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *read_bytes(int fd, char *line_str)
{
char *buff;
int read_value;
if (line_str == NULL)
line_str = ft_calloc(1, 1);
if (line_str == NULL)
return (NULL);
buff = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
if (buff == NULL)
return (NULL);
read_value = 1;
while (read_value > 0)
{
ft_bzero(buff, BUFFER_SIZE + 1);
read_value = read(fd, buff, BUFFER_SIZE);
if (read_value == -1)
return (free(buff), free(line_str), NULL);
line_str = ft_strjoin_free(line_str, buff);
if (ft_strchr(line_str, '\n') != 0)
break ;
}
return (free (buff), line_str);
}
char *ft_str_trim_line(char *line_str)
{
char *buff;
int i;
int j;
i = 0;
j = 0;
if (line_str == NULL || ft_strlen(line_str) == 0)
return (NULL);
while (line_str[i] != '\n' && line_str[i])
i++;
if (ft_strchr(line_str, '\n'))
i++;
buff = ft_calloc(i + 1, sizeof(char));
if (buff == NULL)
return (NULL);
while (line_str[j] != '\n' && line_str[j])
{
buff[j] = line_str[j];
j++;
}
if (line_str[j] == '\n')
buff[j] = '\n';
return (buff);
}
char *ft_str_trim_front(char *line_str)
{
char *new_line_str;
int i;
int j;
i = 0;
j = 0;
if (line_str == NULL)
return (NULL);
while (line_str[i] != '\n' && line_str[i])
i++;
if (line_str[i] == '\0')
return (free (line_str), NULL);
new_line_str = ft_calloc(ft_strlen(line_str) - i + 1, sizeof(char));
if (new_line_str == NULL)
return (NULL);
if (ft_strchr(line_str, '\n'))
i++;
while (line_str[j + i] != '\0')
{
new_line_str[j] = line_str[j + i];
j++;
}
free (line_str);
return (new_line_str);
}
char *get_next_line(int fd)
{
static char *line_str;
char *ret_buff;
ret_buff = NULL;
if (BUFFER_SIZE < 1 || fd < 0)
return (NULL);
line_str = read_bytes(fd, line_str);
ret_buff = ft_str_trim_line(line_str);
line_str = ft_str_trim_front(line_str);
return (ret_buff);
}