#include "string.h"
#include "stdio.h"
#include "alloc.h"
#include "stdlib.h"
#define N 10 /*预定义关键字数目*/
#define M 10 /*keyword的长度*/
struct linelist
{
int linenum;
struct linelist *next;
};
struct keyword
{
struct string *string1;
int num;
struct linelist *head,*tail;
}keyword1[N];
struct string
{char string2[M];
}string3[N]={'/0'};
FILE *fp=NULL;
int row=0;
void init() /*初始化所定义的结构体*/
{
int i;
for (i=0;i<N;i++)
{keyword1[i].num=0;
keyword1[i].string1=string3[i].string2;
keyword1[i].head=NULL;
keyword1[i].tail=NULL;
}
}
void fileopen()
{
char filename[30];
for (;;)
{
printf("请输入要查找关键字的文件:");
scanf("%s",filename);
if ((fp=fopen(filename,"r"))==NULL)
printf("不能打开此文件!请重新输入!\n");
else
break;
}
}
void inputkeyword()
{
int i;
for (i=0;i<N;i++)
{printf("请输入要查找的关键字:");
scanf("%s",string3[i].string2);
}
}
void compare(Array)
char Array[];
{
int i;
struct linelist *p,*q;
for (i=0;i<N;i++)
{ if(!strcmp(Array,string3[i].string2))
{ keyword1[i].num++;
if (keyword1[i].num==1)
{
p=(struct linelist *)malloc(sizeof(struct linelist));
p->linenum=row;
p->next=NULL;
keyword1[i].head=p;
keyword1[i].tail=p;
}
else
if (row!=keyword1[i].tail->linenum)
{
q=(struct linelist *)malloc(sizeof(struct linelist));
q->linenum=row;
q->next=NULL;
keyword1[i].tail->next=q;
keyword1[i].tail=q;
}
}
}
}
void loadcmp(Array)
char Array[];
{
int i,j;
char *p,*q,temp[20];
q=Array;
while (*q!='\n')
{ p=q;
while (*q!='\n')
{
if (*q==' ')
{ p++;
q++;
}
if (*q!=' ')
{q++;
if (*q==' ')break;
}
}
j=q-p;
for (i=0;i<j;i++)
{ temp[i]=*p;
p++;
}
temp[j]='\0';
compare(temp);
}
}
void readline()
{
char buffer[41];
while (!feof(fp))
{row++;
fgets(buffer,40,fp);
loadcmp(buffer);
}
}
void showresult()
{
int i;
struct linelist *p;
printf("\n\n\n");
printf("结果:\n");
for (i=0; i<N; i++)
{
printf("%s",string3[i].string2);
printf(" ");
printf("出现 %d 次",keyword1[i].num);
printf(" ");
printf("他们所在行:");
p=keyword1[i].head;
while (p!=NULL)
{ printf("%3d",p->linenum);
p=p->next;
}
printf("\n");
}
}
void destroy()
{ int i;
struct linelist *p,*q;
for (i=0; i<N; i++)
{
p=keyword1[i].head;
while (p!=NULL)
{ q=p;
p=p->next;
free(q);
}
}
fclose(fp);
}
main()
{ init();
fileopen();
inputkeyword();
readline();
showresult();
destroy();
}