-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
105 lines (96 loc) · 2.25 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: msodor <msodor@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/12 16:48:25 by msodor #+# #+# */
/* Updated: 2022/12/22 13:26:25 by msodor ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_first(char *stat)
{
char *line;
int i;
int j;
i = 0;
j = 0;
if (!stat[i])
return (NULL);
while (stat[i] != '\n' && stat[i])
i++;
if (stat[i] == '\n')
line = malloc(i + 2);
else
line = malloc(i + 1);
if (!line)
return (NULL);
while (j < i)
{
line[j] = stat[j];
j++;
}
if (stat[j] == '\n')
line[j++] = '\n';
line[j] = '\0';
return (line);
}
char *get_rest(char *stat)
{
int j;
int i;
char *rest;
j = 0;
i = 0;
while (stat && stat[i] && stat[i] != '\n')
i++;
if (stat[i] == '\0')
{
free(stat);
return (NULL);
}
if (stat[i] == '\n')
i++;
rest = malloc(ft_strlen(stat) - i + 1);
while (stat && stat[i])
rest[j++] = stat[i++];
rest[j] = '\0';
free(stat);
return (rest);
}
char *readfd(int fd, char *stat)
{
int reading_index;
char *buffer;
reading_index = 1;
buffer = (char *)malloc(BUFFER_SIZE + 1);
if (!buffer)
return (NULL);
while (reading_index && ft_strchr(stat, '\n') == 0)
{
reading_index = read(fd, buffer, BUFFER_SIZE);
if (reading_index < 0)
{
free(stat);
free(buffer);
return (NULL);
}
buffer[reading_index] = '\0';
stat = ft_strjoin(stat, buffer);
}
free(buffer);
return (stat);
}
char *get_next_line(int fd)
{
char *line;
static char *stat;
stat = readfd(fd, stat);
if (!stat)
return (NULL);
line = get_first(stat);
stat = get_rest(stat);
return (line);
}