Advertisement
Guest User

Untitled

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