-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredirection.c
66 lines (62 loc) · 1.58 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
#include "headers.h"
int redirection(int redirect, int num_args)
{
for (int l = 0; l < num_args - 1; l++)
{
if (strcmp(argument[l], "<") == 0)
{
int x = open(argument[l + 1], O_RDONLY);
if (x < 0)
{
perror("File error");
return 1;
}
else
{
dup2(x, STDIN_FILENO);
close(x);
}
for (int j = l; j < num_args - 2; j++)
{
strcpy(argument[j], argument[j + 2]);
}
}
if (strcmp(argument[l], ">") == 0)
{
int x = open(argument[l + 1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (x < 0)
{
perror("File error");
return 1;
}
else
{
dup2(x, STDOUT_FILENO);
close(x);
}
for (int j = l; j < num_args - 2; j++)
{
strcpy(argument[j], argument[j + 2]);
}
}
if (strcmp(argument[l], ">>") == 0)
{
int x = open(argument[l + 1], O_WRONLY | O_CREAT | O_APPEND, 0644);
if (x < 0)
{
perror("File error");
return 1;
}
else
{
dup2(x, STDOUT_FILENO);
close(x);
}
for (int j = l; j < num_args - 2; j++)
{
strcpy(argument[j], argument[j + 2]);
}
}
}
return 0;
}