42_get_next_line/get_next_line.c

105 lines
2.2 KiB
C
Raw Normal View History

2022-10-25 20:27:09 -04:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/26 00:52:47 by cchauvet #+# #+# */
2022-11-08 08:49:12 -05:00
/* Updated: 2022/10/28 16:01:01 by cchauvet ### ########.fr */
2022-10-25 20:27:09 -04:00
/* */
/* ************************************************************************** */
2022-10-25 18:44:33 -04:00
#include "get_next_line.h"
char *ft_getstash(int fd)
{
char *str;
int readed;
2022-10-28 07:41:06 -04:00
str = ft_calloc(BUFFER_SIZE + 1, sizeof(char));
2022-10-25 18:44:33 -04:00
if (str == NULL)
return (NULL);
readed = read(fd, str, BUFFER_SIZE);
2022-11-08 08:49:12 -05:00
if (readed < 1)
2022-10-25 18:44:33 -04:00
{
free(str);
return (NULL);
}
return (str);
}
char *ft_getline(int fd)
{
char *stash;
char *buf;
stash = NULL;
2022-10-28 07:41:06 -04:00
buf = NULL;
2022-11-08 08:49:12 -05:00
while (ft_strchr(stash, '\n') == -1)
2022-10-25 18:44:33 -04:00
{
buf = ft_getstash(fd);
if (buf == NULL)
2022-11-08 08:49:12 -05:00
return (stash);
2022-10-26 11:25:43 -04:00
stash = ft_strfjoin(stash, buf);
if (stash == NULL)
return (NULL);
2022-10-25 18:44:33 -04:00
}
return (stash);
}
2022-11-08 08:49:12 -05:00
char *ft_getreturn(char *str)
{
int i;
if (str == NULL)
return (NULL);
i = ft_strchr(str, '\n') + 1;
if (i == 0)
i = ft_strlen(str);
return(ft_strndup(str, i));
}
char *ft_getextra(char *str)
{
int i;
int j;
if (str == NULL)
return (NULL);
i = ft_strchr(str, '\n') + 1;
if (i == 0)
return (NULL);
j = ft_strlen(str + i);
return(ft_strndup(str + i, j));
}
2022-10-25 18:44:33 -04:00
char *get_next_line(int fd)
{
static char *stash = NULL;
char *buf1;
char *buf2;
2022-10-28 07:41:06 -04:00
buf2 = stash;
2022-10-25 18:44:33 -04:00
if (ft_strchr(stash, '\n') == -1)
{
buf1 = ft_getline(fd);
2022-10-28 07:41:06 -04:00
buf2 = ft_strfjoin(stash, buf1);
if (buf2 == NULL)
2022-11-08 08:49:12 -05:00
{
free(buf1);
2022-10-25 18:44:33 -04:00
return (NULL);
2022-11-08 08:49:12 -05:00
}
2022-10-25 18:44:33 -04:00
}
2022-11-08 08:49:12 -05:00
buf1 = ft_getreturn(buf2);
stash = ft_getextra(buf2);
2022-10-28 07:41:06 -04:00
free(buf2);
2022-11-08 08:49:12 -05:00
if (buf1 == NULL)
2022-10-25 18:44:33 -04:00
{
free(stash);
free(buf1);
return (NULL);
}
return (buf1);
}