#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define COUNT_MAX 300
#define STRING_MAX 500
#define WORD_MAX 20
int GetWord( void);
int UpdateWord( void);
int SortWord( void );
int WriteWord( void );
typedef struct WordFrequency_T{
int count;
char word[ COUNT_MAX ];
}WordFrequency_t;
static WordFrequency_t wordfrequency[ COUNT_MAX ];
char buf[ STRING_MAX ],work[STRING_MAX];
char word_string[WORD_MAX];
int flag = 0;
int main(void)
{
FILE *fp1,*fp2;
fp1=fopen("english.txt","r");
fp2=fopen("check.txt","a");
if( fp1 == NULL ){
fprintf( stderr, "ファイルが見つかりません\n");
exit( EXIT_FAILURE );
}
if( fp2 == NULL ){
fprintf( stderr, "ファイル作成エラー\n");
return -1;
}
while( fgets( buf, STRING_MAX, fp1 ) != NULL ){
fprintf(fp2,"%s",buf);
if(flag==1){
strcpy(work,word_string);
strcat(work,buf);
strcpy(buf,work);
flag=0;
}
while(1){
GetWord();
UpdateWord( );
if( *buf =='\0' ){
break;
}
}
}
if( fclose( fp1 ) ){
fprintf( stderr, "クローズに失敗しました\n");
exit( EXIT_FAILURE );
}
if( fclose( fp2 ) ){
fprintf( stderr, "クローズに失敗しました\n");
exit( EXIT_FAILURE );
}
SortWord();
WriteWord();
}
int GetWord( void )
{
char *pbuf, *pstr;
pstr = word_string;
pbuf = buf;
while( *pbuf == ' ' ){
pbuf++;
}
if( *pbuf == '\0' ) {
return 0;
}
if( isdigit( *pbuf ) ){
while( isdigit( *pbuf ) || *pbuf == '.' ){
*pstr++ = *pbuf++;
}
*pstr = '\0';
}else if( isalpha( *pbuf ) ){
while( isalpha( *pbuf ) || ( *pbuf == '\'' ) ){
*pstr++ = *pbuf++;
}
if(*pbuf=='-'&&*(pbuf+1)=='\n'){
flag=1;
}else if(*pbuf=='.'&&isalpha(*(pbuf+1))){
*pstr++ = *pbuf++;
while(isalpha(*pbuf)){
*pstr++ = *pbuf++;
}
}
*pstr='\0';
pbuf++;
}else{
pbuf++;
if(flag!=1)*pstr='\0';
}
strcpy( buf, pbuf );
return 0;
}
int UpdateWord( void )
{
int i, j;
if(flag==1)return 0;
for( i=0; i < COUNT_MAX; i++ ){
if( wordfrequency[i].count <= 0){
strcpy( wordfrequency[ i ].word, word_string );
wordfrequency[i].count = 1;
break;
}
if( !strcmp( wordfrequency[i].word, word_string ) ){
wordfrequency[ i ].count++;
break;
}
}
return 0;
}
int SortWord( void )
{
WordFrequency_t tmp;
int i,j;
for(i=0;wordfrequency[i].count!=0;i++){
for(j=i+1;wordfrequency[j].count!=0;j++){
if(strcmp(wordfrequency[i].word,wordfrequency[j].word)>0){
tmp=wordfrequency[i];
wordfrequency[i]=wordfrequency[j];
wordfrequency[j]=tmp;
}
} }
return 0;
}
int WriteWord( void )
{
int i;
FILE *fp;
fp = fopen( "result.txt", "w");
if( fp == NULL ){
fprintf( stderr, "ファイルが作成できません\n");
return -1;
}
fprintf( fp, "***単語と頻度の一覧表****\n");
fprintf( fp, "***-----------------****\n");
for( i = 1; i < COUNT_MAX; i++){
if( strlen( wordfrequency[ i ].word ) <= 0){
break;
}
fprintf( fp, "%2d %s %4d\n", i, wordfrequency[ i ].word, wordfrequency[ i ].count );
}
if( fclose( fp ) ){
fprintf( stderr, "クローズに失敗しました\n" );
exit( EXIT_FAILURE );
}
return 0;
}