cmd_splitting.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "sh.h"
  2. /*
  3. ** Prevent segfault, checking if str is not empty
  4. ** Arbitrary set value to 50 blocks splitted
  5. ** Count number of splittable char found (only first occurence)
  6. ** Retrieve position of char splittable
  7. ** Allocate and fill new tab
  8. ** Trim blocks
  9. */
  10. char **cmd_splitting(t_e *e, char *cmd, char c)
  11. {
  12. int pos;
  13. int *poss;
  14. int nbr;
  15. char **tabe;
  16. pos = -1;
  17. nbr = 0;
  18. if (ft_strcmp(cmd, "") == 0)
  19. return (NULL);
  20. poss = (int*)malloc(sizeof(int) * 5);
  21. while (cmd[++pos] != '\0')
  22. if (cmd[pos] == c && (pos > 0 ? c != cmd[pos - 1] : 1)\
  23. && is_on_coted_block(e, e->slen + pos) == 1)
  24. poss[nbr++] = pos;
  25. tabe = (char**)malloc(sizeof(char*) * (nbr + 2));
  26. tabe = fill_tabe(tabe, cmd, nbr, poss);
  27. free(poss);
  28. pos = -1;
  29. while (tabe[++pos] != NULL)
  30. tabe[pos] = ft_assign_free_str(tabe[pos], ft_strtrim);
  31. return (tabe);
  32. }
  33. /*
  34. ** Fill tab splitting
  35. ** Handle different cases depending number of splitting char
  36. ** if zero char: do last block
  37. ** if one char: do first and last blocks
  38. ** if more than one char: do three blocks
  39. */
  40. char **fill_tabe(char **tabe, char *cmd, int nbr, int *poss)
  41. {
  42. int i;
  43. int j;
  44. i = -1;
  45. j = -1;
  46. if (nbr != 0)
  47. tabe[++i] = ft_strsub(cmd, 0, poss[++j]);
  48. while (nbr >= 2 && j + 1 < nbr)
  49. {
  50. tabe[++i] = ft_strsub(cmd, poss[j] + 1, poss[j + 1] - poss[j] - 1);
  51. j++;
  52. }
  53. if (nbr == 0)
  54. tabe[++i] = ft_strsub(cmd, 0, ft_strlen(cmd));
  55. else
  56. tabe[++i] = ft_strsub(cmd, poss[j] + 1, ft_strlen(cmd));
  57. tabe[++i] = NULL;
  58. return (tabe);
  59. }
  60. /*
  61. ** detect if current position is located on a coted block
  62. */
  63. int is_on_coted_block(t_e *e, int pos)
  64. {
  65. int b_pos;
  66. b_pos = -1;
  67. while (e->b[++b_pos] != NULL)
  68. if (e->b[b_pos]->begin <= pos && pos <= e->b[b_pos]->end\
  69. && e->b[b_pos]->type != 0)
  70. return (0);
  71. return (1);
  72. }