-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredirection.c
More file actions
130 lines (118 loc) · 3.23 KB
/
redirection.c
File metadata and controls
130 lines (118 loc) · 3.23 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include "headers.h"
void redirection(char * input_str, char * add_root)
{
long long int i,j,k,r_flag=0,w_flag=0,len,a_flag=0,temp_var;
len = strlen(input_str);
char command[1000], temp[1000], read_file[1000]="\0", write_file[1000]="\0";
char * token;
struct stat info;
int fd_read,fd_write;
for(i=0;i<len;i++)
{
if(input_str[i]=='<')
{
r_flag=1;
}
if(input_str[i]=='>')
{
if(input_str[i+1]=='>')
{
a_flag=1;
}
else
{
w_flag=1;
}
}
}
if(r_flag==0 && w_flag==0 && a_flag==0)
{
command_selector(input_str,add_root);
}
else
{
int in = dup(0) , out = dup(1);
for(i=0;input_str[i]!='<' && input_str[i]!='>';i++)
{
command[i] = input_str[i];
}
for(;i>0;i--)
{
if(command[i]!=' ')
break;
}
command[i+1]='\0';
if(r_flag!=0)
{
strcpy(temp,input_str);
token = strtok(temp," ");
while(token!=NULL)
{
if(strcmp(token,"<")==0)
{
token = strtok(NULL," ");
if(token!=NULL)
strcpy(read_file,token);
break;
}
token = strtok(NULL," ");
}
if(stat(read_file, &info) < 0)
{
fprintf(stderr, "file does not exist\n");
return;
}
else
{
fd_read = open(read_file , O_RDONLY);
if(fd_read < 0)
{
fprintf(stderr, "Error while opening the file\n");
return;
}
temp_var = dup2(fd_read, 0);
if (temp_var < 0)
{
fprintf(stderr, "Failure of dup2\n");
}
close(fd_read);
}
}
if(w_flag!=0)
{
strcpy(temp,input_str);
token = strtok(temp," ");
while(token!=NULL)
{
if(strcmp(token,">")==0 || strcmp(token,">>")==0)
{
token = strtok(NULL," ");
if(token!=NULL)
strcpy(write_file,token);
break;
}
token = strtok(NULL," ");
}
if(a_flag!=0)
fd_write = open(write_file, O_WRONLY|O_APPEND|O_CREAT, 0644);
else
fd_write = open(write_file, O_WRONLY|O_TRUNC|O_CREAT, 0644);
if(fd_write < 0)
{
fprintf(stderr, "Error while opening the file\n");
return;
}
if (dup2(fd_write, 1) < 0)
{
fprintf(stderr, "Failure of dup2\n");
}
close(fd_write);
}
// printf("cmd:%s \nread:%s \nwrite:%s \n",command,read_file,write_file);
command_selector(command,add_root);
dup2(in , 0);
dup2(out , 1);
close(in);
close(out);
}
}