用BF算法比较两个文本文件是否有匹配内容,代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
FILE *fp1, *fp2;//定义两个文件指针
long long int Slength = 0, Tlength = 0;//定义两个文件长度并初始化
long long int i = 1, j = 1, p = 0, q = 0; //回溯时用
char c1, c2;//用来储存文件里的字符
char Sfilename[30], Tfilename[30];//两个文件的路径
printf("请输入主串文件名:");
scanf("%s", &Sfilename);//输入主串文件的路径
if ((fp1 = fopen(Sfilename, "rb")) == NULL) {//判断主串是否可以打开
printf("该文件不能打开\n");
exit(0);
}
printf("请输入模式串文件名:");
scanf("%s", &Tfilename);//输入模式串串文件的路径
if ((fp2 = fopen(Tfilename, "rb")) == NULL) {//判断模式串是否可以打开
printf("该文件不能打开\n");
exit(0);
}
while (!feof(fp1)) {//计算主串长度
fgetc(fp1);
Slength++;
}
while (!feof(fp2)) {//计算模式串长度
fgetc(fp2);
Tlength++;
}
rewind(fp1);//使文件指针指向文件开头
rewind(fp2);
while (i < Slength && j < Tlength) {//BF算法
c1 = fgetc(fp1);
c2 = fgetc(fp2);
if (c1 == c2) {
i++;
j++;
q++;
p = q;
} else if (p != 0) {
fseek(fp1, -i + p, 1);
fseek(fp2, -j, 1);
i = i - j + 2;
j = 1;
p = 0;
} else {
fseek(fp2, -j, 1);
i = i - j + 2;
j = 1;
}
}
if (j >= Tlength)
printf("匹配成功\n");
else
printf("匹配失败\n");
fclose(fp1);//关闭文件
fclose(fp2);
return 0;
}