-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplit_unquoted.c
105 lines (94 loc) · 2.35 KB
/
split_unquoted.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* ************************************************************************** */
/* */
/* :::::::: */
/* split_unquoted.c :+: :+: */
/* +:+ */
/* By: sde-rijk <[email protected]> +#+ */
/* +#+ */
/* Created: 2021/12/13 10:23:06 by sde-rijk #+# #+# */
/* Updated: 2022/01/18 10:28:37 by sde-rijk ######## odam.nl */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "Libft/libft.h"
#include <stdio.h> //TODO remove
static int ft_words(char *s, char c, const int *quoted);
static char *ft_copy(char *arr, char *s, char c, const int *quoted);
static void ft_next_word(char **s, char c, int **quoted);
char **ft_split_unquoted(char const *s, char c, const int *quoted)
{
char **arr;
int words;
int i;
if (!s)
return (0);
i = 0;
words = ft_words((char *)s, c, quoted);
arr = malloc((words + 1) * sizeof(char *));
if (!arr)
return (0);
while (i < words)
{
arr[i] = ft_copy(arr[i], (char *)s, c, quoted);
if (!arr[i])
{
ft_free_ptr_array((void **)arr);
return (0);
}
ft_next_word((char **)&s, c, (int **)"ed);
i++;
}
arr[i] = NULL;
return (arr);
}
static int ft_words(char *s, char c, const int *quoted)
{
int w;
w = 0;
while (*s)
{
while (*s == c && !*quoted)
{
s++;
quoted++;
}
if (*s)
w++;
while (!(*s == c && !*quoted) && *s)
{
quoted++;
s++;
}
}
return (w);
}
static char *ft_copy(char *arr, char *s, char c, const int *quoted)
{
int len;
while (*s == c && !*quoted)
{
quoted++;
s++;
}
len = 0;
while (s[len] && !(s[len] == c && !quoted[len]))
len++;
arr = malloc((len + 1) * sizeof(char));
if (!arr)
return (0);
ft_strlcpy(arr, s, len + 1);
return (arr);
}
void ft_next_word(char **s, char c, int **quoted)
{
while (**s == c && !**quoted)
{
(*s)++;
(*quoted)++;
}
while (!(**s == c && !**quoted) && **s)
{
(*s)++;
(*quoted)++;
}
}