WordCount
程序要求需要统计文本文件中的字符数,单词数,行数信息。
定义一个统计信息的函数int *getCharNum(char *fileName,int *totalNum),形参为文件名称以及统计得到的字符数,单词数,行数,返回值为totalNum;
使用了fgets(buf,size,fp)函数,遇到EOF则返回;按行读取;每一行结束处理换行字符“\n”也算该行字符;对于大小为size的buf,最多只读取size-1个字节;自动地把buf中最后一个字符后添加一个“/0”;函数代码如下:
int *getCharNum(char *fileName, int *totalNum) { int charcount = 0; int rowcount = 0; int wordcount = 0; int lastIsBlank = 0; int slen; char c; char s[10]; FILE *fp; fp = fopen("fileName", "r"); if (fp == NULL) { printf("the file can not open\n"); return NULL; } else while (fgets(s, 10, fp)!= NULL) { slen = strlen(s); for (int i = 0; i < slen; i++) { c = s[i]; if (c == ' ' || c == '\t') { if (!lastIsBlank) { wordcount++; lastIsBlank = 1; } } if (c == '\n' || c == '\r') { rowcount++; lastIsBlank = 0; } if (c == ',' || c == '!' || c == '.' || c == '#' || c == '|' || c == '%' || c == '=' || c == '&' || c == '*' || c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == '<' || c == '>' || c == ';' || c == '/') { charcount++; lastIsBlank = 1; } } } totalNum[0] = wordcount; totalNum[1] = rowcount; totalNum[2] = charcount; return totalNum; }
主函数部分,通过输入需要分析的文件的名字,调用函数,完成分析。
void main() { char fileName[30]; int totalNum[3]; printf("Input file name\n"); scanf("%s",fileName); if (getCharNum(fileName, totalNum)) { printf("单词数为%d\n", totalNum[0]); printf("回车数为%d\n", totalNum[1]); printf("字符数为%d\n", totalNum[2]); } else printf("error\n"); system("pause"); }
运行测试
以为在coding上传就可以,所以没有写博客。后来是同学说才知道,从这件事我总结!一定要跟同学多沟通!!