summaryrefslogtreecommitdiff
path: root/readall.c
diff options
context:
space:
mode:
Diffstat (limited to 'readall.c')
-rw-r--r--readall.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/readall.c b/readall.c
new file mode 100644
index 0000000..3dd976f
--- /dev/null
+++ b/readall.c
@@ -0,0 +1,56 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* readall.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: kdx <kdx @student.42angouleme.fr +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2022/10/10 07:51:08 by kdx #+# #+# */
+/* Updated: 2022/10/10 08:07:42 by kdx ### ########.fr */
+/* */
+/* ************************************************************************** */
+
+#include "libft/libft.h"
+#include "readall.h"
+#include <unistd.h>
+
+/* always free src */
+static char *realloc_buf(char *src, size_t size)
+{
+ char *cpy;
+ size_t i;
+
+ cpy = ft_calloc((size + 1) * READALL_BSIZE, sizeof(char));
+ if (cpy == NULL)
+ return (ft_free(src));
+ i = -1;
+ while (++i < size * READALL_BSIZE)
+ cpy[i] = src[i];
+ ft_free(src);
+ return (cpy);
+}
+
+char *readall(int fd)
+{
+ char *buf;
+ int read_rv;
+ size_t read_cnt;
+
+ buf = realloc_buf(NULL, 0);
+ if (buf == NULL)
+ return (NULL);
+ read_cnt = 0;
+ read_rv = 1;
+ while (read_rv && buf != NULL)
+ {
+ read_rv = read(fd, buf + read_cnt * READALL_BSIZE, READALL_BSIZE);
+ read_cnt++;
+ if (read_rv < 0)
+ return (ft_free(buf));
+ else
+ buf = realloc_buf(buf, read_cnt);
+ if (read_rv != READALL_BSIZE)
+ return (buf);
+ }
+ return (buf);
+}