/*
Name: 文件操作演示
Copyright:
Author:
Date: 05-01-15 21:33
Description:
从文件中读入文章并分解单词
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10000
struct {
char word[60];//存储单词的字符串
int num; //单词个数
} Dictionary[MAX];
int Comp(const void *a, const void *b);
int BuildDic(char map[][60], int n);
void PrintDic(int n);
int main(void)
{
FILE *fp;
int i, top, lenDic;
char map[MAX][60] = {0};
char str[60];
char ch;
if((fp=fopen("abc.txt","rt"))==NULL)
{
printf("can not open file 2\n");
exit(0);
}
top = i = 0;
while ((ch = fgetc(fp)) != EOF)
{
if ((ch >= 'A' && ch <='Z') || (ch >= 'a' && ch <='z'))
{
if (ch >= 'A' && ch <='Z') //全部转化为小写字母
{
ch = ch - 'A' + 'a';
}
str[i++] = ch;
}
else if (i > 0)
{
str[i] = '\0';
strcpy(map[top++], str);
i = 0;
}
}
if (i > 0) //记录最后一个单词
{
str[i] = '\0';
strcpy(map[top++], str);
}
// for (i=0; i<top; i++)
// {
// printf("%s\t", map[i]);
// }
// printf("\n\n");
qsort(map, top, sizeof(map[0]), Comp);
// for (i=0; i<top; i++)
// {
// printf("%s\t", map[i]);
// }
// printf("\n\n");
lenDic = BuildDic(map, top);
PrintDic(lenDic);
fclose(fp);
return 0;
}
int Comp(const void *a,const void *b)
{
return strcmp((char *)a, (char *)b);//升序排序
}
int BuildDic(char map[][60], int n)
{
int i, top = -1;
strcpy(Dictionary[++top].word, map[0]);
Dictionary[top].num = 1;
for (i=1; i<n; i++)
{
if (strcmp(map[i], Dictionary[top].word) == 0)
{
++Dictionary[top].num;
}
else
{
strcpy(Dictionary[++top].word, map[i]);
Dictionary[top].num = 1;
}
}
return top+1;
}
void PrintDic(int n)
{
int i;
for (i=0; i<n; i++)
{
if (Dictionary[i].num >= 10)
printf("%s\t%d\n", Dictionary[i].word, Dictionary[i].num);
}
}
文件操作演示
最新推荐文章于 2022-11-18 21:09:15 发布