diff --git a/ft_getline.c b/ft_getline.c index 3404a92..108da1a 100644 --- a/ft_getline.c +++ b/ft_getline.c @@ -6,7 +6,7 @@ /* By: tmaze +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/07 15:12:59 by tmaze #+# #+# */ -/* Updated: 2019/03/08 14:11:15 by tmaze ### ########.fr */ +/* Updated: 2019/03/17 17:25:19 by tmaze ### ########.fr */ /* */ /* ************************************************************************** */ @@ -19,7 +19,7 @@ static char *supercat(char **s1, char *buff) if ((tmp = ft_strjoin(*s1, buff)) == NULL) return (NULL); ft_strdel(s1); - ft_bzero(buff, BUFF_SIZE + 1); + ft_strclr(buff); *s1 = tmp; return (*s1); } @@ -30,7 +30,7 @@ static int flush_buff(char **line, char *buff) { if ((*line = ft_strdup(buff)) == NULL) return (-1); - ft_bzero(buff, BUFF_SIZE + 1); + ft_strclr(buff); } else if (*line != NULL) if (supercat(line, buff) == NULL) @@ -41,25 +41,44 @@ static int flush_buff(char **line, char *buff) return (0); } +static int get_from_buf(char **line, char *buf, char **tmp) +{ + if ((*tmp = ft_strchr(buf, '\n')) != NULL) + *tmp[0] = '\0'; + if (flush_buff(line, buf) != 0) + return (-1); + if (*tmp != NULL) + ft_memmove(buf, &(*tmp)[1], ft_strlen(&(*tmp)[1]) + 1); + if (*tmp != NULL) + return (1); + return (0); +} + int ft_getline(char **line) { - char buff[BUFF_SIZE + 1]; + static char buf[BUFF_SIZE + 1] = "\0"; + char *tmp; int ret; - int i; if (line == NULL) return (-1); *line = NULL; - ft_bzero(buff, BUFF_SIZE + 1); - i = 0; - while ((ret = read(0, &(buff[i]), 1)) == 1 && buff[i] != '\n') - { - if (++i > BUFF_SIZE && flush_buff(line, buff) != 0) + tmp = NULL; + if (buf[0] == '\0') + ft_bzero(buf, BUFF_SIZE + 1); + else if (buf[0] != '\0' && (ret = get_from_buf(line, buf, &tmp)) != 0) + return (ret); + while (tmp == NULL && (ret = read(0, buf, BUFF_SIZE)) > 0) + if ((tmp = ft_strchr(buf, '\n')) == NULL && flush_buff(line, buf) != 0) return (-1); - if (i > BUFF_SIZE) - i = 0; + if (tmp != NULL) + { + tmp[0] = '\0'; + if (flush_buff(line, buf) != 0) + return (-1); + ft_memmove(buf, &tmp[1], ft_strlen(&tmp[1]) + 1); } - if (ret == 0 && i != 0 && flush_buff(line, buff) != 0) + else if (ret > 0 && flush_buff(line, buf) != 0) return (-1); - return (line != NULL); + return (line != NULL && ret > 0); }