42_get_next_line/get_next_line.c

100 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-10-28 07:41:06 -04:00
/* Updated: 2022/10/28 13:37:18 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);
if (readed < 0)
{
free(str);
return (NULL);
}
return (str);
}
ssize_t ft_strchr(char *str, char c)
{
size_t i;
if (str == NULL)
return (-1);
i = 0;
while (str[i] != c && str[i] != '\0')
i++;
2022-10-26 11:25:43 -04:00
if (str[i] == '\0')
2022-10-25 18:44:33 -04:00
return (-1);
return (i);
}
char *ft_getline(int fd)
{
char *stash;
char *buf;
size_t i;
stash = NULL;
2022-10-28 07:41:06 -04:00
buf = NULL;
2022-10-25 18:44:33 -04:00
i = 0;
2022-10-26 11:25:43 -04:00
while (ft_strchr(stash + i, '\n') == -1)
2022-10-25 18:44:33 -04:00
{
2022-10-26 11:25:43 -04:00
i = i + ft_strlen(buf);
2022-10-25 18:44:33 -04:00
buf = ft_getstash(fd);
if (buf == NULL)
return (NULL);
2022-10-26 11:25:43 -04:00
if (buf[0] == '\0')
{
free(buf);
2022-10-25 18:44:33 -04:00
break ;
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);
}
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);
if (buf1 == NULL)
return (NULL);
2022-10-28 07:41:06 -04:00
buf2 = ft_strfjoin(stash, buf1);
if (buf2 == NULL)
2022-10-25 18:44:33 -04:00
return (NULL);
}
2022-10-28 07:41:06 -04:00
buf1 = ft_strndup(buf2, ft_strchr(buf2, '\n') + 1);
stash = ft_strndup(buf2 + ft_strchr(buf2, '\n') + 1, ft_strlen(buf2));
free(buf2);
2022-10-25 18:44:33 -04:00
if (stash == NULL || buf1 == NULL)
{
free(stash);
free(buf1);
return (NULL);
}
return (buf1);
}