我正在尝试解决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;
}
提前感谢。
答案 0 :(得分:6)
fseek (fp, 0, position);
肯定是错的,fseek
的论据应该是:
换句话说,它应该是:
fseek (fp, position, SEEK_SET);
而且,顺便说一句,你应该总是检查可能失败的函数的返回代码,即使你认为它不会发生。您可能希望根据当前标准position
long int
。它可能不会对小文件产生任何明显的差异,但是一旦你开始处理大于普通整数可以处理的文件,你就会遇到麻烦。
答案 1 :(得分:2)
fseek()的争论是倒退的吗?