Image
WELCOME TO MY HOMEPAGE
ぽてとのC言語練習中ページ
Image

Word.c ver.008 のソースです。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#define MAXCHAR 64
#define MAXWORD 256

typedef struct tnode{
  char word[MAXCHAR];
  /* int count=0; */
  int count;
  struct tnode *left;
  struct tnode *right;
}Node;


Node* makeNode(const char *str){
  /* ノード作成 */
  Node *root;
  root=(Node *)malloc(sizeof(Node));

  strcpy(root->word, str);
  root->count=1;
  root->left=root->right=NULL;

  return root;
}

Node* addNode(Node* p, const char *str){
  /* ノード追加処理 */

  if (p==NULL){   /*今いるところが空欄なら新ノードを作成*/
    p=makeNode(str);
  }
  else if (!strcmp(str, p->word))
    p->count++;
  else if (strcmp(str, p->word)<0)
    p->left=addNode(p->left, str);
  else
    p->right=addNode(p->right, str);

  return p;
}

void TraverseNode(const Node *p){
  /* 解析と出力*/
  if (p!=NULL){
    TraverseNode(p->left);
    printf("%s %4d\n", p->word, p->count);
    TraverseNode(p->right);
  }
}
/*******以下ver0.08で変更した個所の一覧です。***************
 ○メイン関数内で宣言するNODE型の変数をnodeのみにしました。
 ○ポインタ配列を削除。
 ○読み込み終了にfeof()関数を使用しました。
 ○addNode()に渡す前にtemp[]にターミネータを追加しています。
**********************************************************/

int main(void){

 char temp[MAXCHAR];
	
 FILE *fp;
 unsigned int i=0;
 char c;
	
 Node *node=NULL;

  fp=fopen("file1.txt","r");
	
 if (fp==NULL){
  printf("ファイルオープンに失敗しました。\n");
  return -1;
 }

  while (!feof(fp) && j<=MAXWORD){

  c=fgetc(fp);
	
  if (isalpha(c)) {  /*英文字が来た時*/
   temp[i]=c;
   i++;
    }
  else if (i==0){/*英文字でなく、なおかつ以前も英文字でなかった時*/
	 ; 
  }
   else{ /*英文字でなく、なおかつ前が英文字であった時*/
   temp[i]='\0';
   node=addNode(node, temp);   /*単語をaddNode関数に渡す*/
   i=0;
     }
  }
 fclose(fp);
 TraverseNode(node);
 return 0;
}


トップページへ戻る