-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirs.c
129 lines (119 loc) · 2.98 KB
/
redirs.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* redirs.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fulloa-s <fulloa-s@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/07 10:20:59 by vspinell #+# #+# */
/* Updated: 2021/10/28 16:11:50 by fulloa-s ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
size_t ft_countredir2(char *str, t_term *term)
{
size_t i;
size_t count;
i = 0;
count = 0;
while (str && str[i])
{
ft_checkchar(term, str, i);
if ((str[i] == 60 || str[i] == 62)
&& (term->single_q == 0 && term->double_q == 0))
count++;
i++;
}
return (count);
}
int ft_checkfile2(char ***cmd, int x, t_term *term)
{
if (ft_nredir_count((*cmd)[x - 1], ">>") > 0)
{
ft_clearpath((*cmd)[x]);
term->i = open((*cmd)[x], O_RDWR | O_APPEND | O_CREAT, 0644);
if (term->i == -1)
return (0);
dup2(term->i, 1);
}
else if (ft_nredir_count((*cmd)[x - 1], "<<") > 0)
{
ft_clearpath((*cmd)[x]);
if (ft_redir_imput(term, cmd) == -1)
return (-1);
}
return (1);
}
int ft_check_file(char ***cmd, int x, t_term *term)
{
int ret;
ret = 1;
if (ft_nredir_count((*cmd)[x - 1], ">") > 0)
{
ft_clearpath((*cmd)[x]);
term->i = open((*cmd)[x], O_RDWR | O_CREAT | O_TRUNC, 0644);
dup2(term->i, 1);
}
else if (ft_nredir_count((*cmd)[x - 1], "<") > 0)
{
ft_clearpath((*cmd)[x]);
term->i = open((*cmd)[x], O_RDONLY);
if (term->i == -1)
ret = ft_notfound((*cmd)[x]);
else
dup2(term->i, 0);
}
else
ret = ft_checkfile2(cmd, x, term);
ft_matrix_remove(cmd, (*cmd)[x - 1]);
ft_matrix_remove(cmd, (*cmd)[x - 1]);
return (ret);
}
int ft_handle_remaninquote(t_term *term, char ***cmd, int check, int n)
{
int i;
i = 0;
if (check != -1)
{
while ((*cmd)[check][i])
{
if ((*cmd)[check][i] == 39 || (*cmd)[check][i] == 34)
{
(*cmd)[check] = ft_remove_char((*cmd)[check], i);
continue ;
}
if (!(*cmd)[check][i])
break ;
i++;
}
}
i = -1;
while (cmd && (*cmd)[++i])
{
if (ft_countredir2((*cmd)[i], term) > 0)
n++;
}
return (n);
}
int ft_manageredir(t_term *term, char ***cmd)
{
int y;
int n;
int check;
n = 0;
check = ft_check_specialcase(cmd);
if (ft_countredir(term->prompt) > 0)
{
n = ft_handle_remaninquote(term, cmd, check, n);
while (n--)
{
y = 0;
while (ft_countredir2((*cmd)[y], term) == 0 && (*cmd)[y])
y++;
if (ft_check_file(cmd, y + 1, term) == -1)
return (-1);
}
}
ft_quoteclean(cmd);
return (1);
}