-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
113 lines (102 loc) · 2.33 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
112
113
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: brpereir <brpereir@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/05/19 18:51:05 by brpereir #+# #+# */
/* Updated: 2023/06/08 18:44:08 by brpereir ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *clean_line(char *str)
{
size_t i;
size_t j;
char *temp;
i = 0;
j = 0;
if (!str[0])
return (NULL);
while (str[i] && str[i] != '\n')
i++;
if (str[i] == '\n')
i++;
temp = (char *)malloc(sizeof(char) * (i + 1));
while (j < i)
{
temp[j] = str[j];
j++;
}
temp[i] = 0;
return (temp);
}
static char *str_rest(char *str)
{
size_t i;
char *temp;
char *start;
if (!*str)
{
free(str);
return (NULL);
}
start = str;
while (*str && *str != '\n')
str++;
if (*str == '\n')
str++;
i = 0;
while (str[i] && str)
i++;
temp = (char *)malloc(sizeof(char) * (i + 1));
temp[i] = 0;
while (i-- > 0)
temp[i] = str[i];
free(start);
return (temp);
}
static char *get_text(char *str, int fd)
{
char *temp;
int nbytes;
temp = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!temp)
return (NULL);
nbytes = 1;
while (nbytes > 0 && !ft_strchr(str))
{
nbytes = read(fd, temp, BUFFER_SIZE);
if (nbytes == -1)
{
free (temp);
free (str);
return (NULL);
}
temp[nbytes] = 0;
str = join_string(str, temp);
}
free (temp);
return (str);
}
char *get_next_line(int fd)
{
static char *str;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
str = get_text(str, fd);
if (!str)
return (NULL);
line = clean_line(str);
str = str_rest(str);
return (line);
}
// int main(void)
// {
// int fd;
// fd = open("a.txt", O_RDONLY);
// printf("%s\n", get_next_line(fd));
// return (0);
// }