-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
118 lines (99 loc) · 2.82 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
114
115
116
117
118
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zkharbac <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/02 16:58:31 by zkharbac #+# #+# */
/* Updated: 2024/12/04 11:50:18 by zkharbac ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
static char *append_read(char **str, int fd)
{
char buffer[BUFFER_SIZE + 1];
char *tmp;
int br;
if (!str || fd < 0 || BUFFER_SIZE <= 0)
return NULL;
br = 1;
while (br != 0 && (!*str || ft_strchr(*str, '\n') == NULL))
{
br = read(fd, buffer, BUFFER_SIZE);
if (br < 0)
{
free(*str);
return NULL;
}
buffer[br] = '\0';
tmp = ft_strjoin(*str, NULL);
free(*str);
*str = ft_strjoin(tmp, buffer);
free(tmp);
}
return (*str);
}
static char *get_line(char *line)
{
int i = 0;
if (!line || ft_strlen(line) == 0)
return NULL;
while (line[i] != '\n' && line[i] != '\0')
i++;
if (line[i] == '\n')
i++;
return ft_substr(line, 0, i);
}
static char *rest_func(char *reminder)
{
int i = 0, j = 0;
char *temp;
if (!reminder)
return NULL;
while (reminder[i] != '\n' && reminder[i] != '\0')
i++;
if (reminder[i] == '\n')
i++;
if (reminder[i] == '\0')
{
free(reminder);
return NULL;
}
temp = malloc(ft_strlen(reminder) - i + 1);
if (!temp)
return NULL;
while (reminder[i])
temp[j++] = reminder[i++];
temp[j] = '\0';
free(reminder);
return temp;
}
char *get_next_line(int fd)
{
static char *reminder = NULL;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return NULL;
reminder = append_read(&reminder, fd);
if (!reminder)
return NULL;
line = get_line(reminder);
reminder = rest_func(reminder);
return line;
}
// int main()
// {
// int fd = open("test.txt", O_RDONLY);
// if (fd < 0)
// {
// perror("Error opening file");
// return 1;
// }
// char *line;
// line = get_next_line(fd);
// line = get_next_line(fd);
// printf("%s",line);
// free(line);
// return 0;
// }