-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirect.c
75 lines (59 loc) · 1.4 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
#include "redirect.h"
#include "headers.h"
#include "cmdhandle.h"
#include "main.h"
int parseRedirect(char ** parsed, int args)
{
int i;
for(i = 0; i < args; i++)
{
if(!strcmp(parsed[i], "<"))
{
return 1;
}
if(!strcmp(parsed[i], ">"))
{
return 2;
}
if(!strcmp(parsed[i], ">>"))
{
return 3;
}
}
}
void redirect(char ** parsed, int args)
{
int i, stdoutSave = -1, stdinSave = -1, inFd = -1, outFd = -1, flag;
flag = parseRedirect(parsed, args);
if (flag == 1)
{
stdinSave = dup(STDIN_FILENO);
inFd = open(parsed[0], O_RDONLY, 0644);
if(inFd < 0)
perror("Error opening input file");
else
dup2(inFd, STDIN_FILENO);
}
else if (flag == 2)
{
stdoutSave = dup(STDOUT_FILENO);
outFd = open(parsed[2], O_CREAT | O_WRONLY | O_TRUNC, 0644);
if(outFd < 0)
perror("Error opening output file");
else
dup2(outFd, STDOUT_FILENO);
}
else if (flag == 3)
{
stdoutSave = dup(STDOUT_FILENO);
outFd = open(parsed[2], O_CREAT | O_WRONLY | O_APPEND, 0644);
if(outFd < 0)
perror("Error opening output file");
else
dup2(outFd, STDOUT_FILENO);
}
else
{
cmdhandle(parsed, args);
}
}