Advertisement
ThisIsMac

Untitled

Jan 11th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* ************************************************************************** */
  2. /*                                                                            */
  3. /*                                                        :::      ::::::::   */
  4. /*   get_next_line.c                                    :+:      :+:    :+:   */
  5. /*                                                    +:+ +:+         +:+     */
  6. /*   By: jmaiquez <marvin@42.fr>                    +#+  +:+       +#+        */
  7. /*                                                +#+#+#+#+#+   +#+           */
  8. /*   Created: 2016/01/07 15:42:58 by jmaiquez          #+#    #+#             */
  9. /*   Updated: 2016/01/11 18:12:56 by jmaiquez         ###   ########.fr       */
  10. /*                                                                            */
  11. /* ************************************************************************** */
  12.  
  13. #include "get_next_line.h"
  14.  
  15. static char     *gnl_join(char *dst, char *src)
  16. {
  17.     char    *tmp;
  18.  
  19.     tmp = dst;
  20.     dst = ft_strjoin(tmp, src);
  21.     free(tmp);
  22.     return (dst);
  23. }
  24.  
  25. static int      gnl_read(int const fd, char *save[fd])
  26. {
  27.     int     ret;
  28.     char    buf[BUFF_SIZE + 1];
  29.  
  30.     while (!(ft_strchr(save[fd], '\n')) && (ret = read(fd, buf, BUFF_SIZE)) > 0)
  31.     {
  32.         buf[ret] = '\0';
  33.         save[fd] = gnl_join(save[fd], buf);
  34.     }
  35.     return (ret);
  36. }
  37.  
  38. static int      gnl_copy(int const fd, char *save[fd], char **line)
  39. {
  40.     int     i;
  41.     char    *tmp;
  42.  
  43.     i = 0;
  44.     while (save[fd][i] != '\n' && save[fd][i] != '\0')
  45.         i++;
  46.     *line = ft_strsub(save[fd], 0, i);
  47.     tmp = (char *)malloc(sizeof(*tmp) * (ft_strlen(save[fd]) + 1));
  48.     if (tmp == NULL)
  49.         return (-1);
  50.     ft_strcpy(tmp, &save[fd][i + 1]);
  51.     ft_strclr(save[fd]);
  52.     ft_strcpy(save[fd], tmp);
  53.     return (1);
  54. }
  55.  
  56. int             get_next_line(int const fd, char **line)
  57. {
  58.     static  char    *save[255];
  59.  
  60.     if (fd < 0 || line == NULL || fd > 255)
  61.         return (-1);
  62.     if (save[fd] == NULL)
  63.         save[fd] = ft_memalloc(1);
  64.     if (gnl_read(fd, &(*save)) < 0)
  65.         return (-1);
  66.     if (save[fd][0] == '\0')
  67.     {
  68.         *line = NULL;
  69.         return (0);
  70.     }
  71.     if (gnl_copy(fd, &(*save), line) < 0)
  72.         return (-1);
  73.     return (1);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement