Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zaydek-old/2bdad3c07231e4a83d4af82256d93833 to your computer and use it in GitHub Desktop.
Save zaydek-old/2bdad3c07231e4a83d4af82256d93833 to your computer and use it in GitHub Desktop.
gnl.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zmichels <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/02/28 01:08:57 by zmichels #+# #+# */
/* Updated: 2017/02/28 01:11:12 by zmichels ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *gnl_nconcat(char **as, char *s2, size_t n)
{
char *s1;
if (!(s1 = *as))
return ((*as = ft_strndup(s2, n)));
;
if ((*as = malloc(ft_strlen(s1) + ft_strlen(s2) + 1)))
{
ft_strcpy(*as, s1);
ft_strncat(*as, s2, n);
;
free(s1);
}
return (s1);
}
int gnl_push_line(char *buf, char **line)
{
size_t n;
char c;
if (!gnl_nconcat(line, buf, n = ft_strclen(buf, '\n')))
return (-1);
;
c = buf[n];
ft_memmove(buf, buf + n + 1, BUFF_SIZE);
;
return (c ? 1 : 0);
}
int get_next_line(const int fd, char **line)
{
static char buf[256][BUFF_SIZE + 1];
ssize_t ret;
if (!BUFF_SIZE || read(fd, 0, 0) == -1)
return (-1);
;
*line = 0;
if ((ret = gnl_push_line(buf[fd], line)))
return (ret);
;
while ((ret = read(fd, buf[fd], BUFF_SIZE)) > 0)
if ((ret = gnl_push_line(buf[fd], line)))
return (ret);
;
return (**line ? 1 : ret);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment