get_next_line.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* ************************************************************************** */
  2. /* */
  3. /* ::: :::::::: */
  4. /* get_next_line1.c :+: :+: :+: */
  5. /* +:+ +:+ +:+ */
  6. /* By: bchanot <bchanot@students.42.fr> +#+ +:+ +#+ */
  7. /* +#+#+#+#+#+ +#+ */
  8. /* Created: 2016/01/11 15:09:42 by bchanot #+# #+# */
  9. /* Updated: 2016/11/08 11:13:51 by bchanot ### ########.fr */
  10. /* */
  11. /* ************************************************************************** */
  12. #include "libft.h"
  13. #include <unistd.h>
  14. #include <stdlib.h>
  15. static char *ft_get_line(char *str)
  16. {
  17. int i;
  18. char *line;
  19. i = 0;
  20. if (!str)
  21. return (NULL);
  22. while (str[i] && str[i] != '\n')
  23. i++;
  24. line = ft_strncpy(ft_strnew(i), str, i);
  25. line[i] = 0;
  26. return (line);
  27. }
  28. static char *ft_end_chain(char *str)
  29. {
  30. int i;
  31. char *end_chain;
  32. i = 0;
  33. end_chain = NULL;
  34. if (!str)
  35. return (NULL);
  36. while (str[i] && str[i] != '\n')
  37. i++;
  38. end_chain = ft_strdup(&str[i + 1]);
  39. if (i == (int)ft_strlen(str))
  40. ft_memdel((void **)&end_chain);
  41. ft_memdel((void **)&str);
  42. return (end_chain);
  43. }
  44. static int ft_alloc_gnl(char **save, t_gnl *g)
  45. {
  46. if (!(g->buff = ft_strnew(BUFF_SIZE + 1)))
  47. return (-1);
  48. if (!*save)
  49. {
  50. if (!(*save = ft_strnew(1)))
  51. return (-1);
  52. }
  53. return (1);
  54. }
  55. int get_next_line(const int fd, char **line)
  56. {
  57. static char *save[256] = {NULL};
  58. t_gnl g;
  59. if (((g.ret = 42)) && (ft_alloc_gnl(&save[fd % 256], &g) == -1))
  60. return (-1);
  61. while (!(ft_strchr(save[fd % 256], '\n')) && g.ret > 0)
  62. {
  63. if ((g.ret = read(fd, g.buff, BUFF_SIZE)) == -1)
  64. return (-1);
  65. g.buff[g.ret] = 0;
  66. g.temp = save[fd % 256];
  67. save[fd % 256] = ft_strjoin(save[fd % 256], g.buff);
  68. ft_memdel((void **)&g.temp);
  69. }
  70. ft_memdel((void **)&g.buff);
  71. *line = ft_get_line(save[fd % 256]);
  72. save[fd % 256] = ft_end_chain(save[fd % 256]);
  73. if ((int)ft_strlen(*line))
  74. return (1);
  75. if (g.ret == 0 && !save[fd % 256])
  76. {
  77. ft_memdel((void **)&save[fd % 256]);
  78. return (0);
  79. }
  80. return (1);
  81. }