-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
125 lines (114 loc) · 2.71 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
123
124
125
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pcervill <pcervill@student.42madrid.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/04 16:25:28 by pcervill #+# #+# */
/* Updated: 2022/05/09 15:39:00 by pcervill ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_read_write(int fd, char *save)
{
char *stread;
int sizebuff;
sizebuff = 1;
stread = malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!stread)
return (NULL);
while (!ft_strchr(save, '\n') && sizebuff != 0)
{
sizebuff = read(fd, stread, BUFFER_SIZE);
if (sizebuff == -1)
{
free(stread);
return (NULL);
}
stread[sizebuff] = '\0';
save = ft_strjoin(save, stread);
}
free (stread);
return (save);
}
char *ft_print(char *save)
{
int cont;
char *result;
cont = 0;
if (!save[cont])
return (NULL);
while (save[cont] && save[cont] != '\n')
cont++;
result = malloc(sizeof(char) * (cont + 2));
if (!result)
return (NULL);
cont = 0;
while (save[cont] && save[cont] != '\n' )
{
result[cont] = save[cont];
cont++;
}
if (save[cont] == '\n')
{
result[cont] = '\n';
cont++;
}
result[cont] = '\0';
return (result);
}
char *ft_cleansave(char *save)
{
char *newsave;
int cont;
int cont1;
cont = 0;
while (save[cont] && save[cont] != '\n')
cont++;
if (!save[cont])
{
free(save);
return (NULL);
}
newsave = malloc(sizeof(char) * (ft_strlen(save) - cont + 1));
if (!newsave)
return (NULL);
cont++;
cont1 = 0;
while (save[cont])
newsave[cont1++] = save[cont++];
newsave[cont1] = '\0';
free(save);
return (newsave);
}
char *get_next_line(int fd)
{
static char *save;
char *result;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
save = ft_read_write(fd, save);
if (!save)
return (NULL);
result = ft_print(save);
save = ft_cleansave(save);
return (result);
}
/*int main(void)
{
int fd1;
char *str;
fd1 = open("text.txt", O_RDONLY);
str = get_next_line(fd1);
printf("%s\n", str);
str = get_next_line(fd1);
printf("%s\n", str);
str = get_next_line(fd1);
printf("%s\n", str);
str = get_next_line(fd1);
printf("%s\n", str);
close(fd1);
return (0);
}
*/