#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct {
char word[256]; /*登録単語*/
int count; /*出現回数*/
} words_t;
/*
ファイルfpから単語を読み出し,buffにしまって返す関数
char buff[] 見つかった単語をしまう文字列変数
int size buffの大きさ
FILE *fp ファイルストリーム
単語を読み出すことに成功したら1,そうでなかったら0を返す
*/
int fgetword(char buff[], int size, FILE *fp)
{
static int oldch=0; /*直前に読み込んだ文字*/
int
ch;
/*読み込んだ文字*/
int NowInWord=0; /*単語検出中は1,疑似単語検出中は-1,そうでない時は0*/
int cnt=0; /*読み込んだ文字数カウンタ*/
int foundWord=0; /*単語が見つかったら1,そうでなかったら0*/
while (foundWord==0 && cnt<size-1 && (ch=fgetc(fp)) != EOF) {
/*単語が見つかっておらず,かつ読み込み文字数がbuffの大きさより小さく,
かつファイルから1文字読み込んでchに代入して,それがEOFでなかったらの意味。
条件文は左側から順に評価され,継続条件が満たされていないことが
分かった時点でそれ以上の評価は行われなくなる。
(ch=fgetc(fp)) != EOFの評価を最初に行うとこのプログラムでは
正しく動作することができない。なぜかは自分で考えてください。*/
if (NowInWord==1) { /*単語読み込み中ならば*/
if (isalnum(ch)||ch=='_') { /*chがアルファベット,数字または_だったら*/
buff[cnt]=ch;
cnt++;
} else { /*単語の外に出たぞ*/
NowInWord=0;
foundWord=1;
}
} else if (NowInWord==-1) { /*疑似単語読み込み中ならば*/
if (isalnum(ch)||ch=='_') { /*chがアルファベット,数字または_だったら*/
} else { /*疑似単語の外に出たぞ*/
NowInWord=0;
}
} else { /*単語読み込み中でないならば*/
if (isalpha(ch)) { /*chがアルファベットだったら*/
if (isdigit(oldch)) {
NowInWord=-1;
} else {
NowInWord=1;
buff[cnt]=ch;
cnt++;
}
}
}
oldch=ch;
}
buff[cnt]='\0';
return (0<cnt)?1:0;
}
/*********単語データベース(ここから)*********/
/*buffで与えられた単語をwordsに登録する。返す値はこれまで登録された単語の数*/
int registerWord(char buff[], words_t words[])
{
static int nRegistered=0; /*見つけた単語の数*/
int found; /*未登録単語:-1 そうでなかったら見つかった番号*/
int i;
found=-1;
i=0;
while (i<nRegistered && found==-1) {
if (strcmp(words[i].word,buff)==0) found=i;
i++;
}
if (found==-1) { /*未登録済の単語だった*/
strcpy(words[nRegistered].word, buff); /*後ろから前にコピー*/
words[nRegistered].count=1;
nRegistered++;
} else { /*登録済の単語だった*/
words[found].count++;
}
return nRegistered;
}
/*登録領域wordsのデータをNumWords個表示する*/
void printWords(words_t words[], int NumWords)
{
int i;
for (i=0; i<NumWords; i++) {
printf("%3d %-16s : %3d\n",i,words[i].word,words[i].count);
}
}
/*********単語データベース(ここまで)*********/
int main()
{
words_t words[1024]; /*単語登録場所*/
int nRegistered=0; /*見つけた単語の数*/
char fname[256]; /*ファイル名*/
char buff[1024]; /*単語を受け取る文字列*/
FILE *fp; /*ファイルストリーム*/
printf("file name : ");
gets(fname);
fp=fopen(fname,"r");
if (fp==NULL) {
printf("can't open %s\n",fname);
exit(1);
}
while (fgetword(buff,1024,fp)==1) {
/*ファイルから1単語読み込めたら */
/*読み込めた単語buffをデータベースに登録する*/
nRegistered=registerWord(buff, words);
}
fclose(fp);
printWords(words,nRegistered);
}
/*
対象としたtest.c
------------------------------------------------------
#include <stdio.h>
int main()
{
printf("Hello. How are you?\n");
printf("Fine, thanks. And You?\n");
printf("So so.\n");
return 0;
}
------------------------------------------------------
実行結果
file name : test.c
0 include : 1
1 stdio : 1
2 h : 1
3 int : 1
4 main : 1
5 printf : 3
6 Hello : 1
7 How : 1
8 are : 1
9 you : 1
10 n : 3
11 Fine : 1
12 thanks : 1
13 And : 1
14 You : 1
15 So : 1
16 so : 1
17 return : 1
*/
|