From f2e2059042c322ccc5f4a7fc778fc8970a3c776f Mon Sep 17 00:00:00 2001 From: adjoly Date: Sat, 25 May 2024 14:29:30 +0200 Subject: [PATCH] =?UTF-8?q?=E3=80=8C=E2=9C=A8=E3=80=8D=20feat:=20Added=20g?= =?UTF-8?q?et=5Fnext=5Fline=20to=20libft?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libft/Makefile | 3 +- libft/include/libft.h | 9 ++- libft/src/io/get_next_line/get_next_line.c | 74 ++++++++++++++++++++++ 3 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 libft/src/io/get_next_line/get_next_line.c diff --git a/libft/Makefile b/libft/Makefile index 7ed8926..cd89cbd 100644 --- a/libft/Makefile +++ b/libft/Makefile @@ -6,7 +6,7 @@ # By: mmoussou +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2023/12/01 17:11:59 by adjoly #+# #+# */ +/* Updated: 2024/05/25 14:23:08 by adjoly ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +char check_line(char *res, char *buf) +{ + int i; + int j; + + i = 0; + j = 0; + while (res[i] && res[i] != '\n') + i++; + if (res[i] == '\n') + { + i++; + while (res[i]) + { + buf[j] = res[i]; + i++; + j++; + } + buf[j] = 0; + res[i - j] = 0; + return (1); + } + return (0); +} + +char *ft_read_error(char **buf, char *res) +{ + free(*buf); + *buf = NULL; + if (res[0] != 0) + return (res); + free(res); + return (NULL); +} + +char *get_next_line(int fd) +{ + static char *buf; + char *res; + ssize_t bytes_read; + + if (BUFFER_SIZE <= 0 || fd < 0 || fd > 1023) + return (NULL); + if (!buf) + buf = ft_calloc(sizeof(char), BUFFER_SIZE + 1); + res = ft_calloc(1, 1); + while (buf) + { + res = ft_strjoin_free_s1(res, buf); + if (!res) + return (NULL); + if (check_line(res, buf)) + return (res); + bytes_read = read(fd, buf, BUFFER_SIZE); + if (bytes_read < 1) + return (ft_read_error(&buf, res)); + buf[bytes_read] = 0; + } + return (NULL); +}