i did the thing !

rework of ft_getline
This commit is contained in:
Tanguy MAZE 2019-03-18 17:11:38 +01:00
parent d5eecbed88
commit 75ebffddea

View File

@ -6,79 +6,76 @@
/* 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 */
/* Updated: 2019/03/18 17:05:55 by tmaze ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *supercat(char **s1, char *buff)
static int get_last_ind(char *buff)
{
char *tmp;
int i;
if ((tmp = ft_strjoin(*s1, buff)) == NULL)
return (NULL);
ft_strdel(s1);
ft_strclr(buff);
*s1 = tmp;
return (*s1);
i = 0;
while (buff[i] && buff[i] != '\n')
i++;
return (0);
}
static int flush_buff(char **line, char *buff)
{
char *tmp;
int i;
i = get_last_ind(buff);
if (*line == NULL)
{
if ((*line = ft_strdup(buff)) == NULL)
if ((*line = ft_strndup(buff, i)) == NULL)
return (-1);
ft_strclr(buff);
}
else if (*line != NULL)
if (supercat(line, buff) == NULL)
{
if ((tmp = ft_strnew(ft_strlen(*line) + i)) != NULL)
{
ft_strcpy(tmp, *line);
ft_strncat(tmp, buff, i);
ft_strdel(line);
*line = tmp;
}
else
{
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);
}
return (i);
}
int ft_getline(char **line)
{
static char buf[BUFF_SIZE + 1] = "\0";
char *tmp;
static char buff[BUFF_SIZE] = "\0";
int check;
int ret;
int i;
if (line == NULL)
if (line == NULL || BUFF_SIZE < 1)
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)
check = BUFF_SIZE;
while (check == BUFF_SIZE)
{
tmp[0] = '\0';
if (flush_buff(line, buf) != 0)
if (buff[0] == '\0')
{
if ((ret = read(0, buff, BUFF_SIZE)) == -1)
return (-1);
if (ret == 0 && *line == NULL)
return (0);
}
if ((i = flush_buff(line, buff)) == -1)
return (-1);
ft_memmove(buf, &tmp[1], ft_strlen(&tmp[1]) + 1);
check = (buff[i] == '\0' && i != ret) ? BUFF_SIZE : i;
ft_memmove(buff, buff + i + 1, BUFF_SIZE - i);
ft_memset(buff + BUFF_SIZE - i, '\0', i);
}
else if (ret > 0 && flush_buff(line, buf) != 0)
return (-1);
return (line != NULL && ret > 0);
return (1);
}