-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
109 lines (100 loc) · 2.64 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mheinke <mheinke@student.42abudhabi.ae> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/13 11:09:10 by mheinke #+# #+# */
/* Updated: 2023/09/27 13:45:18 by mheinke ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
size_t find_line_ending(char *str, size_t i)
{
while (str[i] && str[i] != '\n')
i++;
if (str[i] == '\n')
i++;
return (i);
}
char *get_string(char *str)
{
char *new_str;
size_t i;
size_t j;
i = 0;
j = 0;
if (str[i] == '\0')
return (free(str), NULL);
i = find_line_ending(str, i);
new_str = (char *)malloc((ft_strlen(str) - i + 1));
if (!new_str)
return (free(new_str), NULL);
while (str[i])
new_str[j++] = str[i++];
new_str[j] = '\0';
if (!new_str[0])
return (free(str), free(new_str), NULL);
free(str);
return (new_str);
}
char *read_the_line(char *str)
{
char *line;
size_t i;
i = 0;
if (!str || str[0] == '\0')
return (NULL);
i = find_line_ending(str, i);
line = (char *)malloc(sizeof(char) * i + 1);
if (!line)
return (NULL);
i = 0;
while (str[i] && str[i] != '\n')
{
line[i] = str[i];
i++;
}
if (str[i] == '\n')
{
line[i] = str[i];
i++;
}
line[i] = '\0';
return (line);
}
char *free_and_null(char *buff1, char *buff2)
{
free(buff1);
free(buff2);
buff2 = NULL;
return (0);
}
char *get_next_line(int fd)
{
static char *read_buffer;
char *read_content;
int read_bytes;
read_bytes = 1;
if (fd < 0 || BUFFER_SIZE <= 0 || BUFFER_SIZE > INT_MAX)
return (NULL);
read_content = (char *)malloc(sizeof(char) * BUFFER_SIZE + 1);
if (!read_content)
return (NULL);
while (!(ft_strchr(read_buffer, '\n')) && read_bytes != 0)
{
read_bytes = read(fd, read_content, BUFFER_SIZE);
if (read_bytes == -1)
{
read_buffer = free_and_null(read_content, read_buffer);
return (NULL);
}
read_content[read_bytes] = '\0';
read_buffer = ft_strjoin(read_buffer, read_content);
}
free(read_content);
read_content = read_the_line(read_buffer);
read_buffer = get_string(read_buffer);
return (read_content);
}