代码如下:
#include
#include
#include
#define Max 200
typedef struct BSTNode* BSTTree;
struct BSTNode{
char W[Max];
int Count;
BSTTree Left,Right;
};
BSTTree T,BT;
//函数声明
void readfile();
void wordread(FILE *fp);
char* wordhandle(char *w);
BSTTree InsertNode(BSTTree T,char *wd);
void InorderPrint(BSTTree T);
BSTTree InsertBSTNode(BSTTree BT,char* wd,int ct);
void InorderPrintBST(FILE* yp,BSTTree BT);
//打开文件
void readfile()
{
char s[Max];
FILE *fp;
FILE *np;
np=fopen("F:\\all_names.txt","w");
fclose(np);
system("dir F:\\hello\\*.txt /s /b >> F:\\all_names.txt");
FILE *hp;
hp=fopen("F:\\all_names.txt","r");
if(hp==NULL)
{
printf("不能打开文件\n");
exit(1);
}
fscanf(hp,"%s",s);
while(!feof(hp))
{
fp=fopen(s,"r");
if(fp==NULL)
{
printf("不能打开文件\n");
exit(1);
}
wordread(fp); //在这里读入数据(填写读入单词函数)
fclose(fp);
fscanf(hp,"%s",s);
}
fclose(hp);
}
//读入单词
void wordread(FILE *fp)
{
char *delim=" @(),.?:;+$!#/\"";
char *p;
char temp[Max];
char wd[Max];
fscanf(fp,"%s",temp);
while(!feof(fp))
{
p=strtok(temp,delim);
while(p!=NULL)
{
strcpy(wd,p);
wordhandle(wd); //对单词进行处理
T = InsertNode(T,wd); //存入链表
p=strtok(NULL,delim);
}
fscanf(fp,"%s",temp);
}
}
//对单词进行处理
char* wordhandle(char *w)
{
int i;
if(w[0]=='\'')
{
for(i=0;i
{
w[i]=w[i+1];
}
}
if(w[0]<='Z'&&w[0]>='A')
{
if(w[1]<='Z'&&w[1]>='A')
{
return w;
}
else
{
w[0]+=32;
}
}
return w;
}
BSTTree InsertNode(BSTTree T,char *wd){
int m;
if(T==NULL){
T = (BSTTree)malloc(sizeof(struct BSTNode));
strcpy(T->W,wd);
T->Count = 1;
T->Left = T->Right = NULL;
}
else if((m=strcmp(T->W,wd))==0){
T->Count++;
}
else if(m>0){
T->Left = InsertNode(T->Left,wd);
}
else if(m<0){
T->Right = InsertNode(T->Right,wd);
}
return T;
}
void InorderPrint(BSTTree T){
if(T){
BT=InsertBSTNode(BT,T->W,T->Count); //将单词输入到第二个BST中;
InorderPrint(T->Left);
InorderPrint(T->Right);
}
}
BSTTree InsertBSTNode(BSTTree BT,char *wo,int ct){
if(BT==NULL){
BT = (BSTTree)malloc(sizeof(struct BSTNode));
BT->Count = ct;
strcpy(BT->W,wo);
BT->Left = BT->Right = NULL;
}
else if(BT->Count
BT->Left = InsertBSTNode(BT->Left,wo,ct);
}
else if(BT->Count>ct){
BT->Right = InsertBSTNode(BT->Right,wo,ct);
}
else if(BT->Count==ct){
BSTTree T1;
T1 = (BSTTree)malloc(sizeof(struct BSTNode));
T1->Count = ct;
strcpy(T1->W,wo);
T1->Left = NULL;
T1->Right = BT->Right;
BT->Right = T1;
}
return BT;
}
void InorderPrintBST(FILE* yp,BSTTree BT){
if(BT){
InorderPrintBST(yp,BT->Left);
{
fprintf(yp,"%s ",BT->W);
fprintf(yp," %d",BT->Count);
fprintf(yp,"\n");
}
InorderPrintBST(yp,BT->Right);
}
}
int main()
{
FILE *yp;
yp = fopen("F:\\结果.txt","w");
readfile();
InorderPrint(T);
InorderPrintBST(yp,BT);
return 0;
}