/* 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); }