文件操作演示

/*
	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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值