From 7fd21dc25dc31a3807962a3d1489fbfcb951b717 Mon Sep 17 00:00:00 2001 From: yctct Date: Tue, 17 Feb 2026 09:20:01 +0100 Subject: Add files, first commit --- ft_getline.c | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 ft_getline.c (limited to 'ft_getline.c') diff --git a/ft_getline.c b/ft_getline.c new file mode 100644 index 0000000..400a23e --- /dev/null +++ b/ft_getline.c @@ -0,0 +1,103 @@ +/* +ft_getline Copyright (C) 2026 yctct + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + + +#include "ft_getline.h" + +char *read_file(int fd, char *buf, char *line, char *stash) +{ + ssize_t bytes_read; + + bytes_read = read(fd, buf, BUFFER_SIZE); + if (bytes_read < 0) + { + free(line); + return (NULL); + } + buf[bytes_read] = 0; + if (bytes_read == 0) + { + if (line[0] != 0) + { + stash[0] = 0; + return (line); + } + else + { + free(line); + return (NULL); + } + } + return (buf); +} + + + +char *eol_is_in_line(char *pivot, char *stash, char *line) +{ + int i; + int j; + char *tmp; + + i = 1; + j = 0; + while (pivot[i] != 0) + stash[j++] = pivot[i++]; + stash[j] = 0; + pivot[1] = 0; + tmp = line; + line = ft_strdup(line); + free(tmp); + return (line); +} + +char *keep_reading(int fd, char *pivot, char *stash, char *line) +{ + char buf[BUFFER_SIZE + 1]; + + while (read_file(fd, buf, line, stash) != 0) + { + line = ft_strjoin(line, buf); + if (!line) + return (NULL); + pivot = ft_strchr(line, EOL); + if (pivot != 0) + return (eol_is_in_line(pivot, stash, line)); + else if (buf[0] == 0) + return (line); + } + return (NULL); +} + +char *ft_getline(int fd) +{ + char *line; + static char stash[BUFFER_SIZE] = "\0"; + char *pivot; + + if ((fd < -1) || (fd > 1024)) + return (NULL); + line = ft_strdup(stash); + if (!line) + return (NULL); + pivot = ft_strchr(line, EOL); + if (pivot != 0) + return (eol_is_in_line(pivot, stash, line)); + else + return (keep_reading(fd, pivot, stash, line)); + return (NULL); +} -- cgit v1.2.3