关键字符串匹配算法

来源:百度知道 编辑:UC知道 时间:2024/06/04 18:36:38
请编写一个带命令行参数的程序grep.c,当运行grep word filename时将统计文本文件filename中word出现的次数,其他运行方式均提示出错误信息。如,运行grep int stdio.h 将输出文件stdio.h文件中int出现的次数,请在程序中加必要的注释。
用C编写哦。谢谢各位高手了哦。。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
int count = 0;
char* buf;
char* pCh;
long len;
FILE* pf;

if(argc != 3)
{
printf("error!\n");
return 1;
}

pf = fopen(argv[2],"r");
if(!pf)
{
printf("Can not open file %s!\n",argv[2]);
return 1;
}
fseek(pf,0L,SEEK_END);
len = ftell(pf);
buf = malloc(len+1);
memset(buf,0,len+1);
rewind(pf);
fread(buf,sizeof(char),len,pf);
fclose(pf);
pCh = buf;
pCh = strstr(pCh,argv[1]);
while(pCh)
{
count++;
pCh = strstr(pCh+1,argv[1]);
}

free(buf);
printf("%d",count);
return 0;
}