minishell
ft_split.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* ft_split.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: kfujita <kfujita@student.42tokyo.jp> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2022/04/18 05:36:53 by kfujita #+# #+# */
9 /* Updated: 2022/04/26 00:14:42 by kfujita ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "../ft_mem/ft_mem.h"
14 #include "ft_string.h"
15 #include <stdlib.h>
16 
17 static size_t count_char(const char *s, char c)
18 {
19  size_t c_count;
20 
21  c_count = 0;
22  while (*s != '\0')
23  {
24  if (*s == c)
25  {
26  while (*s != '\0' && *s == c)
27  s++;
28  if (*s == '\0')
29  break ;
30  c_count++;
31  }
32  else
33  s++;
34  }
35  return (c_count);
36 }
37 
38 static int check_and_handle_alloc_error(char **p_p_ret, size_t p_p_ret_index)
39 {
40  size_t current_index;
41 
42  if (p_p_ret[p_p_ret_index] != NULL)
43  return (0 == 1);
44  current_index = 0;
45  while (current_index < p_p_ret_index)
46  free(p_p_ret[current_index++]);
47  free(p_p_ret);
48  return (0 == 0);
49 }
50 
51 char **ft_split(char const *s, char c)
52 {
53  char **p_p_ret;
54  size_t p_p_ret_index;
55  const char *p_top_to_dup;
56 
57  if (s == NULL)
58  return (ft_calloc(1, sizeof(void *)));
59  while (*s != '\0' && *s == c)
60  s++;
61  p_p_ret = ft_calloc(count_char(s, c) + 2, sizeof(void *));
62  p_p_ret_index = 0;
63  while (p_p_ret != NULL && *s != '\0')
64  {
65  p_top_to_dup = s;
66  while (*s != '\0' && *s != c)
67  s++;
68  p_p_ret[p_p_ret_index]
69  = ft_substr(p_top_to_dup, 0, (size_t)s - (size_t)p_top_to_dup);
70  if (check_and_handle_alloc_error(p_p_ret, p_p_ret_index++))
71  return (NULL);
72  while (*s != '\0' && *s == c)
73  s++;
74  }
75  return (p_p_ret);
76 }
void * ft_calloc(size_t count, size_t size)
Definition: ft_calloc.c:29
static int check_and_handle_alloc_error(char **p_p_ret, size_t p_p_ret_index)
Definition: ft_split.c:38
char ** ft_split(char const *s, char c)
Definition: ft_split.c:51
static size_t count_char(const char *s, char c)
Definition: ft_split.c:17
char * ft_substr(char const *s, unsigned int start, size_t len)
Definition: ft_substr.c:16