problem positioning FILE * with fseek
I'm trying to solve a K&R exercise(7.7).It asks writing a program which takes filenames as arguments and searches them for a particular pattern.For the pattern matching I use the sliding window approach,that is check the first n chars for matching and then shift the "window"(I use an array) one place to the right and check again and so on until the EOF.I believe that I'm not using fseek properly.Am I doing it wrong?
#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 strin开发者_StackOverflow中文版g*/
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;
}
thanks in advance.
fseek (fp, 0, position);
is certainly wrong, the arguments to fseek
should be:
- the file handle.
- the position.
- the "whence" (from where the position is calculated).
In other words, it should be:
fseek (fp, position, SEEK_SET);
And, as an aside, you should generally always check the return code from functions which can fail, even if you don't think it will happen. And you may want to make position
a long int
as per the current standard. It probably won't make any appreciable difference for small files but you will get into trouble once you start handling files that are larger than your normal integers can handle.
Arguments to fseek() are backwards?
精彩评论