-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirection.c
126 lines (117 loc) · 2.46 KB
/
redirection.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
#include "header.h"
void output_redirection(char* input)
{
int len = strlen(input);
int flag = 0;
if(input[len-1]=='&')
{
flag = 1;
input[len-1] = '\0';
}
char* tok = strsep(&input,">");
if(input==NULL)
{
if(flag)
{
char* tok1 = malloc((strlen(tok)+5)*sizeof(char));
strcpy(tok1, tok);
strcat(tok1, " &\0");
input_redirection(tok1);
}
else
{
input_redirection(tok);
}
return;
}
int out_file=-1;
int cout_temp = dup(1);
if(input[0]=='>')
{
strsep(&input,">");
remove_spaces(input);
input = inc_tilda(input);
out_file = open(input,O_WRONLY | O_APPEND | O_CREAT,0644);
if(out_file<0)
{
perror("Redirection output file");
return;
}
}
else
{
remove_spaces(input);
inc_tilda(input);
out_file = open(input,O_WRONLY | O_CREAT | O_TRUNC,0644);
if(out_file<0)
{
perror("Redirection output file");
return;
}
}
dup2(out_file,1);
if(flag==1)
{
char* tok1 = malloc((strlen(tok)+5)*sizeof(char));
strcpy(tok1, tok);
strcat(tok1, " &\0");
input_redirection(tok1);
}
else
{
input_redirection(tok);
}
dup2(cout_temp,1);
close(out_file);
return;
}
void input_redirection(char* input)
{
int len = strlen(input);
int flag = 0;
if(input[len-1]=='&')
{
flag = 1;
input[len-1] = '\0';
}
char* tok = strsep(&input, "<");
if(input==NULL)
{
char* tok1 = malloc((strlen(tok)+5)*sizeof(char));
strcpy(tok1, tok);
if(flag==1)
{
strcat(tok1, " &\0");
execute_input(tok1);
}
else
{
execute_input(tok1);
}
return;
}
int inp_file=0, cin_temp = dup(0);
remove_spaces(input);
input = inc_tilda(input);
inp_file = open(input,O_RDONLY);
if(inp_file<0)
{
perror("Redirection input file");
return;
}
dup2(inp_file,0);
char* tok1 = malloc((strlen(tok)+5)*sizeof(char));
strcpy(tok1, tok);
if(flag==1)
{
strcat(tok1, " &");
execute_input(tok1);
}
else
{
execute_input(tok1);
}
dup2(cin_temp,0);
close(inp_file);
return;
}