-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
122 lines (111 loc) · 2.57 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
119
120
121
122
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: psotto-m <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/25 16:54:47 by psotto-m #+# #+# */
/* Updated: 2022/11/25 16:54:50 by psotto-m ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_next_line(int fd)
{
char *print;
static char *fdarr;
if (fd < 0 || BUFFER_SIZE <= 0)
return (0);
fdarr = read_to_fdarr(fd, fdarr);
if (!fdarr)
return (NULL);
print = line_or_eof(fdarr);
fdarr = set_fdarr(fdarr);
return (print);
}
char *read_to_fdarr(int fd, char *fdarr)
{
char *buffer;
int nbr;
buffer = malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buffer)
return (NULL);
nbr = 1;
while (!ft_strchr(fdarr, '\n') && nbr != 0)
{
nbr = read(fd, buffer, BUFFER_SIZE);
if (nbr == -1)
{
free(buffer);
return (NULL);
}
buffer[nbr] = '\0';
fdarr = ft_strjoin(fdarr, buffer);
}
free(buffer);
return (fdarr);
}
char *line_or_eof(char *fdarr)
{
int i;
char *print;
i = 0;
if (!fdarr[i])
return (NULL);
while (fdarr[i] != '\0' && fdarr[i] != '\n')
i++;
print = (char *)malloc(sizeof(char) * (i + 2));
if (!print)
return (NULL);
i = 0;
while (fdarr[i] != '\0' && fdarr[i] != '\n')
{
print[i] = fdarr[i];
i++;
}
if (fdarr[i] == '\n')
{
print[i] = '\n';
i++;
}
print[i] = '\0';
return (print);
}
char *set_fdarr(char *fdarr)
{
int i;
int k;
char *temp;
i = 0;
k = 0;
while (fdarr[i] != '\0' && fdarr[i] != '\n')
i++;
if (!fdarr[i])
{
free(fdarr);
return (NULL);
}
temp = (char *)malloc(sizeof(char) * (ft_strlen(fdarr) - i + 1));
if (!temp)
return (NULL);
i++;
while (fdarr[i])
temp[k++] = fdarr[i++];
temp[k] = '\0';
free(fdarr);
return (temp);
}
/* int main ()
{
char *tester1;
char *tester2;
int fd1 = open("test1.txt", O_RDONLY);
int fd2 = open("test2.txt", O_RDONLY);
int i = 0;
while(i <= 9)
{
printf("%s", get_next_line(fd1));
printf("%s", get_next_line(fd2));
i++;
}
} */