/* ************************************************************************** */ /* LE - / */ /* / */ /* get_next_line.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: rbousset +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2019/10/29 00:37:39 by rbousset #+# ## ## #+# */ /* Updated: 2019/10/29 00:37:41 by rbousset ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include #include #include #include static uint8_t ft_linecheck(const char *str) { size_t i; i = 0; while (str && str[i]) { if (str[i] == '\n') return (1); i++; } return (0); } static size_t ft_linelen(const char *str) { size_t i; i = 0; while (str[i] != '\n' && str[i] != '\0') i++; return (i); } static int ft_linedup(int fd, char **str) { char *buff; char *tmp; int ret; if (!(buff = (char *)malloc((BUFFER_SIZE + 1) * sizeof(char)))) return (0); ret = 1; while (!ft_linecheck(*str) && (ret = read(fd, buff, BUFFER_SIZE)) > 0) { buff[ret] = '\0'; tmp = *str; *str = ft_strjoin(tmp, buff); free(tmp); } if (ret < 0) { free(*str); free(buff); return (-1); } free(buff); return (ret); } static int ft_errchck(int fd, char **line, char **str) { if (*str == NULL) *str = ft_nstr(0); if (fd < 0 || !line || BUFFER_SIZE <= 0) { free(*str); return (-1); } return (0); } int get_next_line(int fd, char **line) { static char *str; char *tmp; size_t i; int ret; if (ft_errchck(fd, line, &str) == -1) return (-1); ret = ft_linedup(fd, &str); if (ret < 0) return (-1); i = ft_linelen(str); *line = ft_substr(str, 0, i); tmp = str; if (tmp[0] != '\0' && tmp) str = ft_strdup(tmp + i + (tmp[i] == '\n')); if (ret == 0 && ((str == NULL || str[0] == '\0') || !ft_linecheck(str))) { i = tmp[i]; free(tmp); tmp = NULL; return (i == '\n'); } free(tmp); return (1); }