85 lines
2.3 KiB
C
85 lines
2.3 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_getline.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: tmaze <tmaze@student.42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2019/03/07 15:12:59 by tmaze #+# #+# */
|
|
/* Updated: 2019/03/17 17:25:19 by tmaze ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
|
|
static char *supercat(char **s1, char *buff)
|
|
{
|
|
char *tmp;
|
|
|
|
if ((tmp = ft_strjoin(*s1, buff)) == NULL)
|
|
return (NULL);
|
|
ft_strdel(s1);
|
|
ft_strclr(buff);
|
|
*s1 = tmp;
|
|
return (*s1);
|
|
}
|
|
|
|
static int flush_buff(char **line, char *buff)
|
|
{
|
|
if (*line == NULL)
|
|
{
|
|
if ((*line = ft_strdup(buff)) == NULL)
|
|
return (-1);
|
|
ft_strclr(buff);
|
|
}
|
|
else if (*line != NULL)
|
|
if (supercat(line, buff) == NULL)
|
|
{
|
|
ft_strdel(line);
|
|
return (-1);
|
|
}
|
|
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)
|
|
{
|
|
static char buf[BUFF_SIZE + 1] = "\0";
|
|
char *tmp;
|
|
int ret;
|
|
|
|
if (line == NULL)
|
|
return (-1);
|
|
*line = NULL;
|
|
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 (tmp != NULL)
|
|
{
|
|
tmp[0] = '\0';
|
|
if (flush_buff(line, buf) != 0)
|
|
return (-1);
|
|
ft_memmove(buf, &tmp[1], ft_strlen(&tmp[1]) + 1);
|
|
}
|
|
else if (ret > 0 && flush_buff(line, buf) != 0)
|
|
return (-1);
|
|
return (line != NULL && ret > 0);
|
|
}
|