-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
117 lines (106 loc) · 2.37 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oakoudad <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/17 10:18:24 by oakoudad #+# #+# */
/* Updated: 2021/11/18 15:52:28 by oakoudad ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *get_line(char *r, int fd)
{
char *buffer;
int a;
buffer = (char *)malloc(sizeof(char) * BUFFER_SIZE + 1);
if (!buffer)
return (NULL);
a = 1;
while (a > 0 && ft_strchr(r, '\n') == NULL)
{
a = read(fd, buffer, BUFFER_SIZE);
if (a == 0)
break ;
if (a == -1)
{
free(buffer);
return (NULL);
}
buffer[a] = '\0';
r = ft_strjoin(r, buffer);
}
free(buffer);
return (r);
}
char *ft_affiche_line(char *r)
{
int i;
int j;
char *line;
i = 0;
if (*r == '\0')
return (NULL);
while (r[i] && r[i] != '\n')
i++;
if (r[i] == '\n')
i++;
line = (char *)malloc(sizeof(char) * i + 1);
if (!line)
return (NULL);
j = 0;
while (j < i)
{
line[j] = r[j];
j++;
}
line[j] = '\0';
return (line);
}
char *ft_re(char *r)
{
char *p;
int start;
int j;
start = 0;
while (r[start] && r[start] != '\n')
start++;
if (r[start] == '\n')
start++;
if (r[start] == '\0')
{
free(r);
return (NULL);
}
p = (char *)malloc(sizeof(char) * (ft_strlen(r) - start + 1));
if (!p)
return (NULL);
j = 0;
while (r[start])
p[j++] = r[start++];
p[j] = '\0';
free(r);
return (p);
}
char *get_next_line(int fd)
{
static char *r;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
r = get_line(r, fd);
if (!r)
return (NULL);
line = ft_affiche_line(r);
r = ft_re(r);
return (line);
}
#include <stdio.h>
int main()
{
int fd = open("txt.txt", O_RDONLY);
printf("%s", get_next_line(fd));
printf("%s", get_next_line(fd));
//printf("%%s");
}