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