wc.exe
1、代码来源:http://bbs.chinaunix.net/thread-3753945-1-1.html
2、Windows平台,C语言,VC6.0运行环境
3、关于代码的修改:有bug,该程序可以实现输出出现频率最高的10个单词,但是对于如果出现频率最高的单词数小于10,则系统会报错。修改:由于是用for循环输出高频率单词的相关信息,所以采用判断该数组是否为零,不为0,则输出该单词和出现的次数。关于输入文件名的情况也进行了修改,采用提示用户输入文件名,并判断是否能够打开,能则继续运行,否则就提示。
4、GitHub的代码地址:https://github.com/522623378/hello-world/blob/master/WC
代码:
| #include <stdio.h> | |
| #include <stdlib.h> | |
| /* my program simulate linux command wc */ | |
| /* author: xiaowh0 */ | |
| /* date: 2017-9-25 */ | |
| void my_wc(int [],char); | |
| extern int flag=1; | |
| int main(int argc,char *argv[]) | |
| { | |
| FILE *fp; | |
| int c,i,j; | |
| int res_current[3]; /* res_current[0] represent current file's line,res_current[1] represent current file's word,res_current[2] represent | |
| current file's character */ | |
| int res_total[3]; /* res_total[0] represent all files's line,res_total[1] represent all files's word,res_total[2] represent all files's character */ | |
| for(i=0;i<3;i++) | |
| { | |
| res_current=0; | |
| res_total=res_current; | |
| } | |
| if(argc==1) /* no input file,input come from stdin */ | |
| { | |
| while((c=getchar())!=EOF) | |
| my_wc(res_total,c); | |
| printf("\t%d\t%d\t%d\n",res_total[0],res_total[1],res_total[2]); | |
| } | |
| else | |
| { | |
| j=0; | |
| while(++j<argc) | |
| { | |
| if((fp=fopen(argv[j],"r"))==NULL) | |
| { | |
| printf("Can not open the file %s\n",argv[j]); | |
| exit(0); | |
| } | |
| c=fgetc(fp); | |
| while(c!=EOF) | |
| { | |
| my_wc(res_current,c); | |
| c=fgetc(fp); | |
| } | |
| fclose(fp); | |
| printf(" %d %d %d %s\n",res_current[0],res_current[1],res_current[2],argv[j]); | |
| for(i=0;i<3;i++) | |
| { | |
| res_total+=res_current; | |
| res_current=0; | |
| } | |
| } | |
| printf(" %d %d %d total\n",res_total[0],res_total[1],res_total[2]); | |
| } | |
| } | |
| void my_wc(int res_current[],char c) | |
| { | |
| int flag; | |
| res_current[2]++; | |
| if(c=='\n') | |
| { | |
| res_current[0]++; | |
| } | |
| if(c=='\t' || c== ' ' || c=='\n') | |
| { | |
| if(flag==0) | |
| { | |
| res_current[1]++; | |
| flag=1; | |
| } | |
| } | |
| else | |
| flag=0; | |
| } | |
| from http://bbs.chinaunix.net/thread-3753945-1-1.html |
浙公网安备 33010602011771号