-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_next_line.c
85 lines (78 loc) · 2.28 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sunpark <sunpark@student.42.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/22 16:19:58 by sunpark #+# #+# */
/* Updated: 2020/04/15 14:32:17 by sunpark ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int set_new_str(char **line, char **save)
{
int size;
int locate;
int result;
char *tmp_str;
size = 0;
while ((*save)[size] && (*save)[size] != '\n')
size++;
*line = (char *)malloc(size + 1);
locate = 0;
while (locate < size)
{
(*line)[locate] = (*save)[locate];
locate++;
}
(*line)[locate] = '\0';
result = (((*save)[size] == '\n') ? READ : READ_EOF);
tmp_str = (result ? ft_strpush(*save, size + 1) : NULL);
if (result == READ_EOF && *save)
free(*save);
*save = tmp_str;
return (result);
}
int error_handling(char **save)
{
if (*save)
free(*save);
*save = NULL;
return (ERROR);
}
int final_reset(char **line, char **save)
{
*line = ft_strnul();
if (*save)
free(*save);
*save = NULL;
return (READ_EOF);
}
int get_next_line(int fd, char **line)
{
long long len;
char buff[BUFFER_SIZE + 1];
static char *str[FD_SIZE];
char *tmp_str;
if (fd < 0 || !line || fd >= FD_SIZE || \
BUFFER_SIZE <= 0 || read(fd, buff, 0))
return (ERROR);
if (!str[fd])
str[fd] = ft_strnul();
len = 0;
while (!(ft_strchr(str[fd], '\n')) && \
((len = read(fd, buff, BUFFER_SIZE)) > 0))
{
buff[len] = '\0';
tmp_str = ft_strjoin(str[fd], buff);
if (str[fd])
free(str[fd]);
str[fd] = tmp_str;
}
if (len < 0)
return (error_handling(&(str[fd])));
if (len == 0 && str[fd][0] == '\0')
return (final_reset(line, &(str[fd])));
return (set_new_str(line, &(str[fd])));
}