-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.c
More file actions
108 lines (88 loc) · 2.31 KB
/
parse.c
File metadata and controls
108 lines (88 loc) · 2.31 KB
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
106
107
108
#include "parse.h"
void error(char *message)
{
perror(message);
_exit(1);
}
char *trim_whitespace(char *str)
{
char *end;
while ((unsigned char)*str == ' ')
str++;
if (*str == 0)
return str;
end = str + strlen(str) - 1;
while (end > str && (unsigned char)*end == ' ')
end--;
end[1] = '\0';
return str;
}
void parse_pipes(char command[], int cmd_len, Commands *commands)
{
char *token;
for (int i = 0; i < cmd_len; i++)
{
if (command[i] == '|')
commands->cmd_cnt += 1;
}
commands->cmd_cnt += 1;
commands->cmds = malloc(commands->cmd_cnt * sizeof(char *));
for (int i = 0; i < commands->cmd_cnt; i++)
{
commands->cmds[i] = malloc(MAX_CMD_LEN * sizeof(char));
if (i == 0)
token = strtok(command, "|");
else
token = strtok(NULL, "|");
token = trim_whitespace(token);
strcpy(commands->cmds[i], token);
}
}
char *parse_redirect(char command[], Process *process)
{
char *token;
char *output_file;
char *input_file;
/* CASOS PARA PREVER
* 1) quando > vem antes de <
* 2) quando tem mais de uma saída (>)
*/
token = strtok_r(command, ">", &output_file);
token = trim_whitespace(token);
if (strcmp(output_file, "") == 0)
output_file = NULL;
else
output_file = trim_whitespace(output_file);
process->output = output_file;
token = strtok_r(token, "<", &input_file);
token = trim_whitespace(token);
if (strcmp(input_file, "") == 0)
input_file = NULL;
else
input_file = trim_whitespace(input_file);
process->input = input_file;
return token;
}
void parse_args(char command[], Process *process)
{
char *token;
int index = 0;
for (int i = 0; i < MAX_ARGS; i++)
process->argv[i] = NULL;
token = strtok(command, " ");
strcpy(process->cmd, token);
process->argv[index] = token;
while (token != NULL)
{
index++;
if (index > MAX_ARGS + 1)
error("Numero maximo de argumentos excedido!");
token = strtok(NULL, " ");
process->argv[index] = token;
}
}
void parse_command(char command[], Process *process)
{
command = parse_redirect(command, process);
parse_args(command, process);
}