-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.c
84 lines (70 loc) · 1.5 KB
/
parse.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
#include "tinyshell.h"
static size_t current = 0;
static size_t count_(char **strings)
{
size_t count = 0;
while (strings[count])
count++;
return (count);
}
static void skip_delimiters(char const *s, char d)
{
while (s[current] && s[current] == d)
current++;
}
static size_t word_length(char const *s, char d)
{
size_t length = 0;
while (s[current] && (s[current++] != d || !d))
length++;
return (length);
}
static char **assign_(char **words, char const *s, char d)
{
size_t start, length, count;
current = count = 0;
skip_delimiters(s, d);
while (s[current])
{
start = current;
length = word_length(s, d);
if (length)
words[count++] = strndup(&s[start], length);
skip_delimiters(s, d);
}
words[count] = NULL;
return (words);
}
static char **get_word_spaces(char const *s, char d)
{
size_t count;
current = count = 0;
skip_delimiters(s, d);
while (s[current])
{
word_length(s, d);
count++;
skip_delimiters(s, d);
}
return (malloc(sizeof(char *) * ++count));
}
static char **split(char const *source, char delimiter)
{
char **words = get_word_spaces(source, delimiter);
return (assign_(words, source, delimiter));
}
char ***parse(char *line)
{
char ***commands;
char **splitted = split(line, '|');
size_t count;
count = count_(splitted);
pipe_count = count - 1;
commands = malloc(sizeof(char **) * (count + 1));
commands[count] = NULL;
while (count-- > 0)
commands[count] = split(splitted[count], ' ');
free_strings(splitted);
free(line);
return (commands);
}