#include
#include
#define MAXSIZE 20
void swap(char *a, char *b)
{
char temp=*a;
*a=*b;
*b=temp;
}
char * itoa(int num)
{
char * strNum=(char *)calloc(MAXSIZE,sizeof(char));
int i,j;
do
{
strNum[i++]='0'+num%10;
num/=10;
} while (num);
strNum[i]='\0';
for(--i,j=0;j
return strNum;
}
int * next_generate(char * p)
{
int * pnext=(int *)calloc(MAXSIZE,sizeof(int));
pnext[0]=-1;
int k,j;
for(k=-1,j=0;p[j];)
{
if(k==-1||p[j]==p[k])
{
j++;
k++;
pnext[j]=k;
}
else
k=pnext[k];
}
return pnext;
}
void KMP(FILE * IN, char * p)
{
int *Jnext=next_generate(p);
int j=0,row=0,col=0;
char c=fgetc(IN);
while(c!=EOF&&p[j])
{
if(j==-1||p[j]==c)
{
j++;
c=fgetc(IN);
col++;
if(c=='\n')
{
col=0;
row++;
}
}
else
{
j=Jnext[j];
}
}
if(!p[j])
{
printf("I find it,below is its position\nrow:%d\ncol:%d",row+1,col-j+1);
return;
}
printf("There is no such number in the file");
}
int main()
{
FILE * ptr=fopen("data.txt","r");
char * strNum=itoa(100);
int * a=next_generate(strNum);
KMP(ptr,strNum);
return 0;
}