Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

6.設計一個程式可以做全文搜尋的功能。首先讓使用者輸入一個文字檔案檔�

0 views
Skip to first unread message

肉腳布

unread,
Jan 3, 2007, 12:21:53 AM1/3/07
to
6. 設計一個程式可以做全文搜尋的功能。首先讓使用者輸入一個文字檔案檔名,程式開啟這個文字檔後,再讓使用者輸入欲搜尋的字串,程式就從檔案的開頭開始搜尋
6. 設計一個程式可以做全文搜尋的功能。首先讓使用者輸入一個文字檔案檔名,程式開啟這個文字檔後,再讓使用者輸入欲搜尋的字串,程式就從檔案的開頭開始搜尋這個字串,找到符合的字串時便紀錄一次,最後輸出找到符合字串的個數。
(提示:以一個指標來記錄檔案位置指標,另設一個變數當作字串的指標(事實上不是一個指標,可用一個整數變數來記錄目前字串比較的位置)。使用fseek找尋符合第一個字元相同的位置,接著比較第二個字元、第三個字元……若與欲找尋的字串完全吻合,則用一個變數來累計次數,若比較過程中有不符合的字元,便不再比對,使用fseek將指標移到下一個字元,繼續重複剛剛的比對動作。請觀察下頁的圖解。)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char c,filename[20];
printf("請輸入文字檔檔名:");
scanf("%s",filename);
FILE *fp;
if ((fp=fopen(filename,"r"))==NULL) {
printf("File can't be opened!\n");
exit(0);
}
printf("文字檔內容如下:\n");
while((c=fgetc(fp))!=EOF) printf("%c",c);
fseek(fp,0,SEEK_SET);

int spos=0, count=0, slen;
char search[20],cmp[20];

printf("請輸入欲搜尋的文字:");
scanf("%s",search);
slen=strlen(search);
while(fgets(cmp,slen+1,fp)!=NULL)
{
if(!strcmp(cmp,search))
{
count++;
spos+=slen;
}
else
spos++;
fseek(fp,spos,SEEK_SET);
}
printf("%s共出現%d次\n",search,count);
}


--
◎ [1;31m龍 [32m貓 [33m資 [34m訊 [35m天 [36m地 [0m( [1mbbs.mgt.ncu.edu.tw [0m)
◎[ [1;33;46mbrucetsao [0m]From: 140.115.82.88

0 new messages