文件上机综合题(2019.12.30)

文件上机综合题
  1. Write a program to count occurrences(出现次数) of each different word in a file, sort according to the description, and write the result to another file. Filenames are specified in the command line.
    1、Format of the command line: cmd inputFile outputFile
    2、Sorting criteria: from most frequent word to rare one. If two words have same occurrences, they are outputted in lexicographical order.
    3、Input file size limitation: 10K
    4、Output file format: “word: occurrences” for each word in each line
    For example:
    an input file a.txt :
    ass sdwd ssd ssda wqw ass
    ass as a aa a a aa a a a
    command line: cmd a.txt b.txt
    b.txt:
    a: 6
    ass: 3
    aa: 2
    as: 1
    sdwd: 1
    ssd: 1
    ssda: 1
    wqw: 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 5000
#define LEN 80

typedef struct
{
    char word[LEN];
    int cnt;
} PAIR;

int index(char * w, PAIR *pairs_, int n)
{

    int i;
    for(i=0; i<n; i++)
        if(strcmp(w,pairs_[i].word)==0) return i;
    return -1;
}

int cmp(PAIR pa, PAIR pb){ //按照题意对两个结构体类型进行比较

     if(pa.cnt != pb.cnt)
        return pa.cnt-pb.cnt;
     else
        return -strcmp(pa.word,pb.word);
}

//冒泡排序
void bubble_sort(PAIR arr[], int len)
{
    int i, j;  PAIR temp;
    for (i = 0; i < len - 1; i++)
        for (j = 0; j < len - 1 - i; j++)
        if (cmp(arr[j], arr[j+1]) < 0 )
        {
            temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
        }
}

int main (int argc, char *argv[])
{

    PAIR  pairs[N];
    char w[LEN];
    int i,n=0,idx;
    //FILE *fin = fopen(argv[1],"r");
    //FILE *fout = fopen(argv[2],"w");

    FILE *fin = fopen("d:\\data.txt","r");
    FILE *fout = fopen("d:\\output.txt","w");

    while (fscanf(fin,"%s",w)==1)
        if((idx = index(w,pairs,n))!=-1) pairs[idx].cnt++;
        else
        {
            strcpy(pairs[n].word,w);
            pairs[n++].cnt=1;
        }
    //sort
    bubble_sort(pairs,n);
    //output
    for(i=0; i<n; i++)
        fprintf(fout,"%s: %d\n",pairs[i].word,pairs[i].cnt);

    fclose(fin);
    fclose(fout);


}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值