#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUF_SIZE 2048
char pat_str[BUF_SIZE];
char text_str[BUF_SIZE];
char *pat=pat_str;
char *text=text_str;
int skip[BUF_SIZE];
int pat_fd=0;
int text_fd=0;
void openFile()
{
pat_fd=open("pat.txt",O_RDWR);
if(pat_fd<0)
{
perror("Pat Open");
exit(1);
}
text_fd=open("text.txt",O_RDWR);
if(text_fd<0)
{
perror("Text Open");
exit(1);
}
}
void readFile()
{
int pat_count=0;
int text_count=0;
pat_count=read(pat_fd,pat_str,BUF_SIZE);
if(pat_count<=0)
{
perror("Pat Read");
exit(2);
}
sprintf(pat,"%s",pat_str);
printf("Pat==%s\n",pat);
text_count=read(text_fd,text_str,BUF_SIZE);
if(text_count<=0)
{
perror("Text Read");
exit(2);
}
sprintf(text,"%s",text_str);
printf("Text==%s\n",text);
}
void closeFile()
{
close(pat_fd);
close(text_fd);
}
int main()
{
int len1=0;
int len2=0;
int i=0,j=0;
openFile();
readFile();
len1=strlen(text)-1;
len2=strlen(pat)-1;
char *text_end=text+len2-1;
char *pat_end=pat+len2-1;
while(1)
{
for(i=0;i<len2;i++)
{
if(*(text_end-i)!=*(pat_end-i))
{
for(j=i;j<len2;j++)
{
if(*(text_end-i)==*(pat_end-j))
{
printf("text_end==%c move %d\n",*(text_end-i),j-i);
text_end=text_end+j-i;
//printf("text_end==%c",*text_end);
i=-1;
j=0;
getchar();
break;
}
//printf("No %c\n",*(pat_end-j));
}
if(j==len2)
{
printf("Move len2(%d)\n",len2);
text_end+=len2;
i=-1;
j=0;
}
}
if((text_end-text)>=len1)
{
printf("Has no this string in text\n");
closeFile();
return -1;
}
}
if(i==len2)
{
printf("Form text[%d] OK\n",text_end-text-len2+1);
closeFile();
return 0;
}
}
}