-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
114 lines (103 loc) · 2.46 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ahouari <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/28 08:55:33 by ahouari #+# #+# */
/* Updated: 2021/11/28 15:11:18 by ahouari ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include<fcntl.h>
char *change_text(char *text)
{
char *newtext;
size_t len;
size_t i;
len = 0;
while (text[len] != '\n' && text[len] != '\0')
len++;
if (text[len] == '\0')
{
free(text);
return (NULL);
}
i = 0;
newtext = (char *)malloc(sizeof(char) * (ft_strlen(text) - len + 1));
if (newtext == NULL)
return (NULL);
while (text[len++] != '\0')
newtext[i++] = text[len];
newtext[i] = '\0';
free(text);
return (newtext);
}
char *get_line(char *text)
{
char *line;
size_t len;
size_t i;
len = 0;
if (text[0] == '\0')
return (NULL);
while (text[len] != '\n' && text[len] != '\0')
len++;
if (text[len] == '\n')
len++;
line = (char *)malloc(sizeof(char) * (len + 1));
if (line == NULL)
return (NULL);
i = 0;
while (i < len)
{
line[i] = text[i];
i++;
}
line[i] = '\0';
return (line);
}
char *read_line(char *text, int fd)
{
char *buff;
int n;
buff = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (buff == NULL)
return (NULL);
n = 1;
while (!(ft_strchr(text, '\n')) && n != 0)
{
n = read(fd, buff, BUFFER_SIZE);
if (n == -1)
{
free(buff);
return (NULL);
}
buff[n] = '\0';
text = ft_strjoin(text, buff);
}
free(buff);
return (text);
}
char *get_next_line(int fd)
{
static char *text;
char *line;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
text = read_line(text, fd);
if (text == NULL)
return (NULL);
line = get_line(text);
text = change_text(text);
return (line);
}
int main(int ac, char **av)
{
char *line;
int fd1;
fd1 = open("file", O_RDONLY);
get_next_line(fd1);
return (0);
}