-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpipe_grep.c
44 lines (35 loc) · 1007 Bytes
/
pipe_grep.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
/*
* usage: ./a.out text_pattern input_file output_file
* Executes the command "grep text_pattern < input_file > output_file"
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
int ifp, ofp;
if (argc == 4)
{
// grep on text_pattern
char *grep_args[] = {"grep", argv[1], NULL};
// open input and output files
ifp = open(argv[2], O_RDONLY);
ofp = open(argv[3], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
// duplicate input file to stdin
dup2(ifp, 0);
// duplicate output file to stdout
dup2(ofp, 1);
// close unused input file descriptor
close(ifp);
// close unused output file descriptor
close(ofp);
// execute grep
execvp("grep", grep_args);
}
else
{
printf("usage: %s text_pattern input_file output_file\n", argv[0]);
}
}