-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
112 lines (101 loc) · 2.41 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: melkholy <melkholy@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/01 06:22:05 by melkholy #+# #+# */
/* Updated: 2022/07/04 08:01:06 by melkholy ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int ft_findnewl(const char *str, int c)
{
int count;
count = 0;
if (!str)
return (0);
while (str[count] && str[count] != (unsigned char)c)
count ++;
if (str[count] == (unsigned char)c)
{
count ++;
return (count);
}
return (0);
}
char *ft_cut_remain(char *line)
{
char *rmn;
int n_line;
if (!line)
return (NULL);
n_line = ft_findnewl(line, '\n');
if (!n_line || !line[n_line])
{
free(line);
return (NULL);
}
rmn = ft_strdup(&line[n_line]);
free(line);
return (rmn);
}
char *ft_cut_tonline(char *line)
{
char *str;
size_t end;
if (!line)
return (NULL);
end = ft_findnewl(line, '\n');
if (!end)
{
str = ft_strdup(line);
return (str);
}
else
{
str = (char *)ft_calloc(end + 1, sizeof(char));
if (!str)
return (NULL);
ft_strlcpy(str, line, (end + 1));
return (str);
}
}
char *ft_readit(int fd, char *read_in)
{
int bytes;
char *str;
bytes = 1;
str = (char *)ft_calloc(BUFFER_SIZE + 1, sizeof(char));
if (!str)
return (NULL);
while (!(ft_findnewl(read_in, '\n')) && bytes > 0)
{
bytes = read(fd, str, BUFFER_SIZE);
if (bytes < 0)
{
free(str);
return (NULL);
}
str[bytes] = '\0';
if (bytes)
read_in = ft_strjoin(read_in, str);
}
free(str);
return (read_in);
}
char *get_next_line(int fd)
{
static char *line;
char *read_in;
read_in = NULL;
if (fd < 0 || fd > 1024 || BUFFER_SIZE < 1)
return (NULL);
line = ft_readit(fd, line);
if (!line)
return (NULL);
read_in = ft_cut_tonline(line);
line = ft_cut_remain(line);
return (read_in);
}