文件导入

grep –v usr result.txt

[c]
/*
Filename: go.c
Author: guozan @SCS-BUPT
Mail: zendo.guo@gmail.com
Date: 2010/5/7
Desciptions: program to complete
grep –v usr < /etc/passwd | wc –l > result.txt
More:
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char infile[] = "/etc/passwd";
int fin = -1;
char outfile[] = "result.txt";
int fout = -1;
int fd[2];
if (pipe(fd) == -1) {
perror("Create pipe");
exit(1);
}
switch (fork()) {
case -1: /* error */
perror("fork");
exit(1);
break;
case 0: /* child */
close(fd[1]);
dup2(fd[0], 0); /* use fd[0] as stdin */
close(fd[0]);
fout = open(outfile, O_CREAT|O_WRONLY, 0666);
if (fout == -1) {
perror("write file out");
exit(1);
}
dup2(fout, 1); /* write to fout */
close(fout);
execlp("wc", "wc", "-l", 0);
fprintf(stderr, "**>>wc failed<<**/n");
exit(1);
break;
default: /* parent */
close(fd[0]);
dup2(fd[1], 1); /* use fd[1] as stdout */
close(fd[1]);
fin = open(infile, O_RDONLY);
if (fin == -1) {
perror("Read file in");
exit(1);
}
dup2(fin, 0); /* read from fin */
close(fin); /* close stdin */
execlp("grep", "grep", "-v", "usr", 0);
fprintf(stderr, "**>>grep failed<<**/n");
exit(1);
break;
}
return 0;
}
[/c]

评论