-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_next_line.c
119 lines (108 loc) · 2.47 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akoudia <akoudia@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/09 11:26:40 by akoudia #+# #+# */
/* Updated: 2022/12/07 22:16:12 by akoudia ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *save_next(char *store)
{
int i;
int j;
char *new_store;
i = 0;
while (store[i] && store[i] != '\n')
i++;
if (!store[i])
return (NULL);
new_store = (char *)malloc(sizeof(char) * (ft_strlen(store) - i));
if (!new_store)
return (NULL);
i++;
j = 0;
while (store[i])
new_store[j++] = store[i++];
new_store[j] = '\0';
return (new_store);
}
char *gline(char *bigline)
{
int i;
char *line;
i = 0;
if (!bigline[i])
return (NULL);
while (bigline[i] && bigline[i] != '\n')
i++;
line = malloc(sizeof(char) * i + 2);
if (!line)
return (NULL);
i = 0;
while (bigline[i] && bigline[i] != '\n')
{
line[i] = bigline[i];
i++;
}
if (bigline[i] == '\n')
{
line[i] = bigline[i];
i++;
}
line[i] = '\0';
return (line);
}
char *reads(int fd, char *str)
{
int i;
char *buffer;
i = 1;
buffer = malloc(sizeof(char) * (BUFFER_SIZE + 1));
if (!buffer)
return (0);
while (i > 0)
{
i = read(fd, buffer, BUFFER_SIZE);
if (i == -1)
{
free(buffer);
free(str);
return (0);
}
buffer[i] = '\0';
str = ft_strjoin(str, buffer);
if (ft_strchr(str, '\n'))
break ;
}
free(buffer);
return (str);
}
char *get_next_line(int fd)
{
char *line;
static char *save;
char *tmp;
if (fd == 1 || fd == 2 || fd == -1 || BUFFER_SIZE <= 0)
return (0);
save = reads(fd, save);
if (!save)
return (NULL);
tmp = save;
line = gline(tmp);
save = save_next(tmp);
free(tmp);
return (line);
}
// int main()
// {
// char *str;
// open("file1.txt",O_RDONLY);
// while ((str=get_next_line(3)) && str != NULL)
// {
// printf("%s", str1);
// }
// }