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
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/19 09:08:36 by cacharle #+# #+# */
/* Updated: 2019/10/20 07:39:13 by cacharle ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include "get_next_line.h"
/*
** if has rest:
** if rest has newline:
** push rest until newline in line, shift rest
** return LINE_READ
** else:
** push rest in line
**
** while can read fd in buf
** if buf has newline:
** push buf until newline in line
** push buf after newline in rest
** return LINE_READ
** push buf in line
**
** return END_OF_FILE
*/
int get_next_line(int fd, char **line)
{
t_bool had_rest;
int ret;
int split_at;
char buf[BUFFER_SIZE + 1];
static char rest[BUFFER_SIZE + 1] = {0};
if (fd < 0 || line == NULL)
return (ERROR);
had_rest = put_rest(line, rest);
while (rest[0] == '\0' && (ret = read(fd, buf, BUFFER_SIZE)) > 0)
{
buf[ret] = '\0';
if ((split_at = find_newline(buf)) != -1)
{
ft_strncpy(rest, buf + split_at + 1, BUFFER_SIZE);
buf[split_at] = '\0';
*line = ft_strappend(*line, buf);
return (*line == NULL ? ERROR : LINE_READ);
}
if ((*line = ft_strappend(*line, buf)) == NULL)
return (ERROR);
}
if (had_rest)
return (LINE_READ);
return (ret == -1 ? ERROR : END_OF_FILE);
}
int put_rest(char **line, char *rest)
{
int split_at;
t_bool had_rest;
had_rest = rest[0] != '\0';
if ((split_at = find_newline(rest)) == -1)
{
*line = malloc(sizeof(char) * (ft_strlen(rest) + 1));
ft_strcpy(*line, rest);
rest[0] = '\0';
return (had_rest);
}
*line = malloc(sizeof(char) * (split_at + 1));
ft_strncpy(*line, rest, split_at);
(*line)[split_at] = '\0';
ft_strncpy(rest, rest + split_at + 1, BUFFER_SIZE);
return (had_rest);
}
int find_newline(char *str)
{
int i;
i = -1;
while (str[++i])
if (str[i] == '\n')
return (i);
return (-1);
}
|