-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirect.c
61 lines (58 loc) · 1.54 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
#include "redirect.h"
void redirect(char *new_cmd)
{
if (strstr(new_cmd, "<"))
{
int in;
for (int i = 0; i < args - 1; i++)
{
if (!strcmp(command[i], "<"))
{
in = open(command[i + 1], O_RDONLY);
if (in < 0)
{
fprintf(stderr,"Error opening input file\n");
return;
}
else
{
dup2(in, STDIN_FILENO);
close(in);
}
command[i] = "";
command[i + 1] = "";
break;
}
}
}
if (strstr(new_cmd, ">"))
{
int out;
for (int i = 0; i < args - 1; i++)
{
if (!strcmp(command[i], ">") || !strcmp(command[i], ">>"))
{
if (!strcmp(command[i], ">>"))
{
out = open(command[i + 1], O_WRONLY | O_CREAT | O_APPEND, 0644);
}
else
{
out = open(command[i + 1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
}
if (out < 0)
{
fprintf(stderr,"Error opening output file\n");
}
else
{
dup2(out, STDOUT_FILENO);
close(out);
}
command[i] = "";
command[i + 1] = "";
break;
}
}
}
}