-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredirection.h
90 lines (86 loc) · 2.19 KB
/
redirection.h
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
#include"headers.h"
#include"global.h"
void changeInputFile(){
int index = 0;
int test = 0;
for(int i = 0; i < argumentNumber ; i++){
if(argumentInput[i][0] == '<' && i >= 1){
index = i;
test = 1;
break;
}
}
if(test == 0){
return;
}
char *fileName = (char *)malloc(VARIABLE_LENGTH * sizeof(char));
strcpy(fileName, argumentInput[index+1]);
for(int i = index ; i < argumentNumber - 2 ; i++){
argumentInput[i] = argumentInput[i + 2];
}
argumentInput[argumentNumber-1] = NULL;
argumentInput[argumentNumber-2] = NULL;
argumentNumber-=2;
int fd = open(fileName, O_RDONLY);
if(fd <= 0){
perror("File Error: ");
return;
}
OriStdIn = dup(0);
dup2(fd, 0);
isStdInChanged = 1;
return;
}
void resetInputFile(){
dup2(OriStdIn, 0);
isStdInChanged = 0;
return;
}
void changeOutputFile(){
int index = 0;
int overwrite = 0;
int test = 0;
for(int i = 0; i < argumentNumber ; i++){
if(argumentInput[i][0] == '>'){
index = i;
if(strcmp(argumentInput[i], ">>")==0){
overwrite = 0;
}else if(strlen(argumentInput[i])==1){
overwrite = 1;
}else{
return;
}
test = 1;
break;
}
}
if(test == 0){
return;
}
char *fileName = (char *)malloc(VARIABLE_LENGTH * sizeof(char));
strcpy(fileName, argumentInput[index+1]);
for(int i = index ; i < argumentNumber - 2 ; i++){
argumentInput[i] = argumentInput[i + 2];
}
argumentInput[argumentNumber-1] = NULL;
argumentInput[argumentNumber-2] = NULL;
argumentNumber-=2;
int fd;
if (overwrite == 1){
fd = open(fileName, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
}else{
fd = open(fileName, O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
}
if (fd == -1)
{
perror("File error");
return;
}
OriStdOut = dup(1);
dup2(fd, 1);
isStdOutChanged = 1;
}
void resetOutputFile(){
dup2(OriStdOut, 1);
isStdOutChanged = 0;
}