我正在尝试解决K&R练习(7.7).它要求编写一个程序,该程序将文件名作为参数并搜索它们以寻找特定模式.对于模式匹配,我使用滑动窗口方法,即检查前n个字符匹配然后将"窗口"(我使用一个数组)移到右边一个地方并再次检查,直到EOF.我相信我没有正确使用fseek.我做错了吗?
#include <stdio.h>
#include <string.h>
int pattern_check(FILE *);
char *pattern="dog";
int
main(int argc,char **argv)
{
FILE *fp;
char *file_name;
int i;
int matchings;
for(i=1;i<argc;i++){
file_name=strdup(argv[i]);
fp=fopen(file_name,"r");
if((matchings=pattern_check(fp))){
printf("%d patterns found in %s\n",matchings,argv[i]);
}
fclose(fp);
}
system(sleep(10000));
return 0;
}
int
pattern_check(FILE *fp)
{
int length=strlen(pattern);
char window[length];
int i,c;
int found=0;
unsigned position=ftell(fp);
window[length]='\0';
while(1){
/*load characters from file to string*/
for(i=0;i<length;i++){
fscanf(fp,"%c",&c);
window[i]=c;
}
/*compare*/
if(strcmp(window,pattern)==0)
found++;
if(feof(fp))
break;
/*move window one to the right*/
fseek(fp,0,position);
position+=1;
}
return found;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
fseek (fp, 0, position);
Run Code Online (Sandbox Code Playgroud)
肯定是错的,fseek应该是:
换句话说,它应该是:
fseek (fp, position, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)
而且,顺便说一句,您通常应该始终检查可能失败的函数的返回代码,即使您认为它不会发生.你可能想按照现行标准制作position一个long int.它可能不会对小文件产生任何明显的差异,但是一旦你开始处理大于普通整数可以处理的文件,你就会遇到麻烦.