统计txt文件中字符数、单词数、行数
- 主体思路
- 利用c的命令行参数传递用户指令
if(argc < 3) { printf("Usage ./wc.exe [-c] [-w] [-l] FILE [-o] Outfile"); exit(0); } for(int count = 1; count < argc; count++) { //判断必需参数 if(!strcmp(argv[count], "-c")) { c = 1; //Method1 } else if(!strcmp(argv[count] ,"-w")) { w = 1; } else if(!strcmp(argv[count] ,"-l")) { l = 1; } else { //搜索输入文件名 inputfile = argv[count]; break; } }- 从测试文件读取内容
fpread = fopen(inputfile,"r"); fread(instr,sizeof(char),Maxchar,fpread); fclose(fpread);- 利用函数处理字符
- 字符处理函数
/* **字符数统计 */ int Charnum(char* str) { int totalchar=0; while(*str++ != '\0') { totalchar++; } return totalchar; }- 文本行处理函数
/* **行数统计 */ int Linenum(char* str) { int linenum = 0; while(*str != '\0') { if(*str++ == '\n') linenum++; } return linenum; }- 单词统计函数
/* **单词统计 */ int Wordnum(char* str) { char* currpt; int count=0; while(*str != '\0') { if(!(((*str>=0x41)&&(*str<=0x5A))||((*str>=0x61)&&(*str<=0x7A)))) { str++; continue; } else { currpt = str+1; do { if(!(((*currpt>=0x41)&&(*currpt<=0x5A))||((*currpt>=0x61)&&(*currpt<=0x7A)))) { count++; str = currpt; break; } }while(*(++currpt) != '\0'); } } return count; } - 将结果写入文件
/* **结果输出 */ fpwrite = fopen(outputfile,"w+"); fwrite(outstr,sizeof(char),strlen(outstr),fpwrite); fclose(fpwrite);实例展示



- 全部代码展示
本文介绍了一个使用C语言编写的程序,该程序能够通过命令行参数接收用户指令,统计指定文本文件中的字符数、单词数及行数,并将结果输出到另一个文件中。文章详细展示了如何解析命令行参数、读取文件内容以及实现字符、单词和行数的统计。
3198

被折叠的 条评论
为什么被折叠?



