summaryrefslogtreecommitdiffstats
path: root/libft/src/get_next_line.c
diff options
context:
space:
mode:
Diffstat (limited to 'libft/src/get_next_line.c')
-rw-r--r--libft/src/get_next_line.c112
1 files changed, 112 insertions, 0 deletions
diff --git a/libft/src/get_next_line.c b/libft/src/get_next_line.c
new file mode 100644
index 0000000..2b2f084
--- /dev/null
+++ b/libft/src/get_next_line.c
@@ -0,0 +1,112 @@
+/* ************************************************************************** */
+/* LE - / */
+/* / */
+/* get_next_line.c .:: .:/ . .:: */
+/* +:+:+ +: +: +:+:+ */
+/* By: rbousset <marvin@le-101.fr> +:+ +: +: +:+ */
+/* #+# #+ #+ #+# */
+/* Created: 2019/10/29 00:37:39 by rbousset #+# ## ## #+# */
+/* Updated: 2019/10/29 00:37:41 by rbousset ### #+. /#+ ###.fr */
+/* / */
+/* / */
+/* ************************************************************************** */
+
+#include <libft.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+
+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[1024];
+ char *tmp;
+ size_t i;
+ int ret;
+
+ if (ft_errchck(fd, line, &str[fd]) == -1)
+ return (-1);
+ ret = ft_linedup(fd, &str[fd]);
+ if (ret < 0)
+ return (-1);
+ i = ft_linelen(str[fd]);
+ *line = ft_substr(str[fd], 0, i);
+ tmp = str[fd];
+ if (tmp[0] != '\0' && tmp)
+ str[fd] = ft_strdup(tmp + i + (tmp[i] == '\n'));
+ if (ret == 0 && ((str[fd] == NULL || str[fd][0] == '\0') || !ft_linecheck(str[fd])))
+ {
+ i = tmp[i];
+ free(tmp);
+ tmp = NULL;
+ return (i == '\n');
+ }
+ free(tmp);
+ return (1);
+}