#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream.h> //for cout
#include <ctype.h>//使用字符函數(shù)
//isalpha(ch),islower(ch),isdigital(ch)
//從一個(gè)文件中取出字符串與另一個(gè)文件比較,計(jì)算字符串在該文件中出現(xiàn)的次數(shù)
//(字符串包含匹配性驗(yàn)證,比如?代表小寫英文字母,*代表小寫英文字母和0-9的數(shù)字),
//第一問要求你用程序?qū)崿F(xiàn)該題目,第二問要求你對(duì)第一問中的程序?qū)憸y(cè)試用例,包括基本
//測(cè)試、邊界測(cè)試,*代表小寫英文字母和0-9的數(shù)字
bool equal(char a,char b)
{
if(a==b) return true;
if(a == '?' && b == '*' || a=='*' && b=='?')
return true;
if((a=='?' && b>=97 && b<=122) || (a>=97 && a<=123 && b=='?'))
return true;
if((a=='*' && b>=97 && b<=122) || (a>=97 && a<=122 && b=='*') || (a=='*' && b>=48 &&b<=57) || (a>=48 && a<=57 && b=='*'))
return true;
return false;
}
int main(int argc,char** argv)
{
char line[30];
FILE *fp;
int i=0,j=0;
if((fp = fopen(argv[1],"r")) != NULL)
{
if(fgets(line,100,fp)== NULL)//實(shí)際上取29個(gè)字符,最后加'\0'
{
printf("fgets error\n");
}
fclose(fp);
}
int length = strlen(line);
int sum = 0;//次數(shù)初始為0
char ch;
if(fopen(argv[2],"r") != NULL)
//在文件2中查找字符串,并計(jì)數(shù)
{
while((ch = fgetc(fp))!= EOF)
{
int test;
test = ftell(fp);
printf("file pointer value:%d\n",test);
if(equal(ch,line[j]))
{
j++;
if(j == length) //字符串匹配到尾部,成功,總數(shù)加1
{
sum+=1;
j =0;
}
}
else //否則的話回溯,重新匹配
{
i= ftell(fp);
fseek(fp,j,1);//向前回溯一個(gè)字符
j= 0;
}
}
}
printf("string %s occurs %d times in file2\n",line,sum);
return sum;
}
/*邊界測(cè)試
設(shè)計(jì)測(cè)試用例時(shí)要考慮邊界輸入和非法輸入,這里統(tǒng)稱為特殊輸入,程序
員在編寫代碼時(shí)也要考慮特殊輸入,要為特殊輸入編寫處理代碼。在實(shí)際工作中,程序員沒有考慮到某些
特殊輸入是很常見的,這也是程序錯(cuò)誤的一個(gè)重要來源。
*/