-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredirect.c
93 lines (87 loc) · 2.49 KB
/
redirect.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* redirect.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ggiannit <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/03 15:29:27 by ggiannit #+# #+# */
/* Updated: 2023/04/17 09:53:24 by ggiannit ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
/* 1 append, 2 create */
int ft_out_file(t_mish *meta, char *filename, int type)
{
if (!filename[0])
return (0);
if (meta->outfile != -2 && meta->outfile != -1)
close(meta->outfile);
if (type == 1)
meta->outfile = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0644);
else if (type == 2)
meta->outfile = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644);
return (1);
}
int ft_in_file(t_mish *meta, char *filename)
{
if (!filename[0])
{
ft_putstr_fd("duckshell: syntax error near \
unexpected token `newline'", 2);
meta->exit_code = 2;
return (0);
}
if (meta->infile != -2 && meta->infile != -1)
close(meta->infile);
meta->infile = open(filename, O_RDONLY);
if (meta->infile <= 0)
{
perror(filename);
meta->exit_code = 1;
return (0);
}
return (1);
}
int ft_red_continue(t_mish *meta, t_cmd *node, int i)
{
if (node->red[i][0] == '<')
{
if (!ft_in_file(meta, &node->red[i][1]))
return (2);
}
else if (node->red[i][0] == '>' && node->red[i][1] == '>')
{
if (!ft_out_file(meta, &node->red[i][2], 1))
return (ft_red_error(meta));
}
else if (node->red[i][0] == '>')
{
if (!ft_out_file(meta, &node->red[i][1], 2))
return (ft_red_error(meta));
}
return (0);
}
int ft_do_red(t_mish *meta, t_cmd *node)
{
int i;
int ecode;
i = -1;
while (node->red && node->red[++i])
{
if (node->red[i][0] == '<' && node->red[i][1] == '<')
{
if (!node->red[i][2])
return (ft_red_error(meta));
if (!ft_in_heredoc(meta, &node->red[i][2]))
return (130);
}
else
{
ecode = ft_red_continue(meta, node, i);
if (ecode)
return (ecode);
}
}
return (0);
}