Untitled


SUBMITTED BY: Guest

DATE: Nov. 23, 2014, 3:28 p.m.

FORMAT: Text only

SIZE: 2.2 kB

HITS: 843

  1. #include <stdlib.h>
  2. #include <unistd.h>
  3. #include "xfunc.h"
  4. #include "libmy.h"
  5. #include "get_next.h"
  6. static int my_get_size(t_buff *stack)
  7. {
  8. int res;
  9. res = 0;
  10. while (stack)
  11. {
  12. res += stack->size;
  13. stack = stack->next;
  14. }
  15. return (res);
  16. }
  17. static char *my_pop(t_buff **stack)
  18. {
  19. int size;
  20. char *res;
  21. t_buff *tmp;
  22. res = NULL;
  23. if ((size = my_get_size(*stack))
  24. && (res = xmalloc((size + 1) * sizeof(*res))))
  25. {
  26. res[size] = '\0';
  27. while (*stack)
  28. {
  29. size = my_get_size(*stack);
  30. my_strncpy(res + (size - (*stack)->size),
  31. (*stack)->str, (*stack)->size);
  32. tmp = *stack;
  33. *stack = (*stack)->next;
  34. free(tmp->str);
  35. free(tmp);
  36. }
  37. }
  38. return (res);
  39. }
  40. static int my_push(t_buff **stack, char *str, int size)
  41. {
  42. t_buff *new;
  43. if (size > 0)
  44. if ((new = xmalloc(sizeof(*new))))
  45. if ((new->str = xmalloc(size * sizeof(*(new->str)))))
  46. {
  47. new->size = size;
  48. my_strncpy(new->str, str, size);
  49. if (*stack)
  50. new->next = *stack;
  51. else
  52. new->next = NULL;
  53. *stack = new;
  54. return (size);
  55. }
  56. return (0);
  57. }
  58. static char *verif(const int fd, t_buff **stack, char *buff, int str_size)
  59. {
  60. if (str_size > 0 && my_push(stack, buff, str_size))
  61. return (get_next_line(fd));
  62. else
  63. return (my_pop(stack));
  64. }
  65. char *get_next_line(const int fd)
  66. {
  67. int i;
  68. char *res;
  69. static t_buff *stack;
  70. int tot_size;
  71. int str_size;
  72. char buff[BUF_SIZE];
  73. if ((i = 0) || stack)
  74. while (i < stack->size)
  75. if (stack->str[i++] == '\n')
  76. {
  77. str_size = stack->size;
  78. tot_size = my_get_size(stack) - str_size;
  79. res = my_pop(&stack);
  80. my_push(&stack, res + tot_size + i, str_size - i);
  81. res[tot_size + i - 1] = '\0';
  82. return (res);
  83. }
  84. if ((str_size = read(fd, buff, BUF_SIZE)) != (-1))
  85. return (verif(fd, &stack, buff, str_size));
  86. free(my_pop(&stack));
  87. return (NULL);
  88. }

comments powered by Disqus