Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. /* ************************************************************************** */
  2. /*                                                                            */
  3. /*                                                        :::      ::::::::   */
  4. /*   get_next_line.c                                    :+:      :+:    :+:   */
  5. /*                                                    +:+ +:+         +:+     */
  6. /*   By: abaidali <abaidali@student.42.fr>          +#+  +:+       +#+        */
  7. /*                                                +#+#+#+#+#+   +#+           */
  8. /*   Created: 2019/10/02 22:50:22 by abaidali          #+#    #+#             */
  9. /*   Updated: 2019/10/13 00:17:58 by abaidali         ###   ########.fr       */
  10. /*                                                                            */
  11. /* ************************************************************************** */
  12.  
  13. #include "get_next_line.h"
  14.  
  15. static int      get_line(char **s, char **line)
  16. {
  17.     int     len;
  18.     char    *tmp;
  19.  
  20.     len = 0;
  21.     while ((*s)[len] != '\n' && (*s)[len] != '\0')
  22.         len++;
  23.     if ((*s)[len] == '\n')
  24.     {
  25.         *line = ft_strsub(*s, 0, len);
  26.         tmp = ft_strdup(&((*s)[len + 1]));
  27.         free(*s);
  28.         *s = tmp;
  29.         if ((*s)[0] == '\0')
  30.             ft_strdel(s);
  31.     }
  32.     else
  33.     {
  34.         *line = ft_strdup(*s);
  35.         ft_strdel(s);
  36.     }
  37.     return (1);
  38. }
  39.  
  40. static int      ft_result(char **s, char **line, int res, int fd)
  41. {
  42.     if (res < 0)
  43.         return (-1);
  44.     else if (res == 0 && s[fd] == NULL)
  45.         return (0);
  46.     else
  47.         return (get_line(&s[fd], line));
  48. }
  49.  
  50. int             get_next_line(const int fd, char **line)
  51. {
  52.     int         status;
  53.     static char *s[MAX_FD];
  54.     char        buf[BUFF_SIZE + 1];
  55.     char        *tmp;
  56.  
  57.     if (fd < 0 || line == NULL)
  58.         return (-1);
  59.     while ((status = read(fd, buf, BUFF_SIZE)) > 0)
  60.     {
  61.         buf[status] = '\0';
  62.         if (s[fd] == NULL)
  63.             s[fd] = ft_strdup(buf);
  64.         else
  65.         {
  66.             tmp = ft_strjoin(s[fd], buf);
  67.             free(s[fd]);
  68.             s[fd] = tmp;
  69.         }
  70.         if (ft_strchr(s[fd], '\n'))
  71.             break ;
  72.     }
  73.     return (ft_result(s, line, status, fd));
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement