summaryrefslogtreecommitdiff
path: root/ft_getline.c
diff options
context:
space:
mode:
authoryctct <yctct@yctct.com>2026-02-17 09:20:01 +0100
committeryctct <yctct@yctct.com>2026-02-17 09:20:01 +0100
commit7fd21dc25dc31a3807962a3d1489fbfcb951b717 (patch)
treec8e48844290a95fe672a09cd48815b39108ea297 /ft_getline.c
Add files, first commitHEADmain
Diffstat (limited to 'ft_getline.c')
-rw-r--r--ft_getline.c103
1 files changed, 103 insertions, 0 deletions
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 <https://www.gnu.org/licenses/>.
+*/
+
+
+#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);
+}