#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
int main()
{
int pipefd[2];
int ret = pipe(pipefd);
if(-1 == ret)
{
perror("pipe");
exit(1);
}
pid_t pid = fork();
if(pid>0)
{
close(pipefd[0]);
int fd = open("/home/linux/dict.txt",O_RDONLY);
if(-1 == fd)
{
perror("open dict");
exit(1);
}
while(1)
{
while(1)
{
char buf[4096]={0};
int rd_ret = read(fd,buf,sizeof(buf));
if(rd_ret<=0)
{
break;
}
write(pipefd[1],buf,rd_ret);
}
lseek(fd,0,SEEK_SET);
}
close(fd);
close(pipefd[1]);
}
else if(0 == pid)
{
close(pipefd[1]);
char wantword[50]={0};
char line_buf[512]={0};
char *arg[2]={NULL};
FILE* fp = fdopen(pipefd[0],"r");
int num = 0;
while(1)
{
num = 0;
printf("input wantword:");
fgets(wantword,sizeof(wantword),stdin);//zoo\n
wantword[strlen(wantword)-1]='\0';
if(0==strcmp(wantword,"#quit"))
{
exit(0);
}
while(1)
{
fgets(line_buf,sizeof(line_buf),fp);//NULL 0
arg[0]=strtok(line_buf," ");
arg[1]=strtok(NULL,"\r");
if(0 == strcmp(wantword,arg[0]))
{
printf("%s:%s\n",arg[0],arg[1]);
break;
}
num++;
if(num>=19661)
{
printf("not find\n");
break;
}
}
}
}
else
{
perror("fork");
exit(1);
}
printf("Hello World!\n");
return 0;
}
程序中的字典路径可以改变