#include <stdio.h>
#include<string.h>
struct Node /*临时存放数据的节点*/
{
char a[8];
};
struct Tree
{
char b[8];
int w;
struct Tree *left;
struct Tree *right;
};
void visit(struct Tree *node)
{
int i;
for(i=0;i<8;i++)
{
if(node->b[i]=='\0')
putchar(' ');
else
printf("%c",node->b[i]);
}
printf(" %d \n",node->w);
}
void print(struct Tree *root) /*中序遍历输出函数*/
{
if(root==NULL)
{return;}
else
{
if((root->left)!=NULL)
{print(root->left);}
visit(root);
if((root->right)!=NULL)
{print(root->right);}
}
}
main()
{
FILE *fp;
struct Node m[400];
struct Tree *root,*p,*q;
char filename[40],ch;
int i,j,k,l;
root=NULL;
for(i=0;i<400;i++)
{
for(j=0;j<8;j++)
{
m[i].a[j]='\0';
}
}
printf("Please input the name of file: "); /*文件读入部分*/
scanf("%s", filename);
fflush(stdin);
if((fp=fopen(filename, "r")) == NULL)
{
printf("Cannot open the file.\n");
exit(0);
}
else
{
i=0;
j=0;
ch=fgetc(fp);
while (ch!=EOF)
{
if(((ch<=122)&&(ch>=97))||((ch<=90)&&(ch>=65))||(ch=' '))
{
if(i>=8)
{
if(ch==' ')
{
i=0;
j++;
ch=fgetc(fp);
continue;
}
else
{
ch=fgetc(fp);
continue;
}
}
if(ch==' ')
{
if(m[j].a[0]!='\0')
{j++;}
i=0;
ch=fgetc(fp);
}
else
{
if((ch>=97)&&(ch<=122))
{ch=ch-32;}
m[j].a[i]=ch;
i++;
ch=fgetc(fp);
}
}
else
{
ch=fgetc(fp);
continue;
}
}
}
fclose(fp); /*文件读入结束*/
l=j;
for(i=0;i<=l;i++) /*二叉树生成部分(非递规)*/
{
if(m[i].a[0]=='\0')
{break;}
else
{
p=(struct Tree *)malloc(sizeof(struct Tree));
p->left=NULL;
p->right=NULL;
for(k=0;k<8;k++)
{p->b[k]='\0';}
p->w=1;
for(k=0;k<8;k++)
{
p->b[k]=m[i].a[k];
}
free(m[i]);
if(root==NULL)
{root=p;}
else
{
q=root;
while(q!=NULL)
{
if((strcmp(q->b,m[i].a))>0)
{
if((q->left)!=NULL)
{
q=q->left;
if((strcmp(q->b,m[i].a))==0)
{
q->w=q->w+1;
q=NULL;
continue;
}
continue;
}
else
{
q->left=p;
q=NULL;
continue;
}
}
if((strcmp(q->b,m[i].a))<0)
{
if((q->right)!=NULL)
{
q=q->right;
if((strcmp(q->b,m[i].a))==0)
{
q->w=q->w+1;
q=NULL;
continue;
}
continue;
}
else
{
q->right=p;
q=NULL;
continue;
}
}
else
{
q->w=q->w+1;
q=NULL;
continue;
}
}
}
}
}
printf("The result is:\nThere are %d words in this file.\n",l+1);
print(root);
getchar();
}