一、题目
已知文件 a.txt 存储若干文本数据,编程统计 a.txt 文件的行数、大写字母个数、小写字母个数、数字字符个数及其他字符的个数。要求如下:
① 定义 countFile()函数:统计文本文件的行数、大写字母个数、小写字母个数、数字字符个数及其他字符的个数。
② 定义 main()函数:打开 a.txt 文件,调用 countFile()函数统计文本文件的行数、大写字母个数、小写字母个数、数字字符个数及其他字符的个数,输出统计结果。
二、程序清单
#include<stdio.h>
#include<stdlib.h>
void countFile(FILE* pfile, int* row, int* capital, int* small, int* num, int* other)
{
while (!feof(pfile))//若文件未结尾,则进入循环
{
char c = fgetc(pfile);
if (c >= 65 && c <= 90)//判断大写字母
(* capital)++;//注意这里一定要加上括号!虽然自增运算符的优先级高,但是前缀自增运算符产生作用的时间晚!
else if (c >= 97 && c <= 122)//判断小写字母
(* small)++;
else if (c >= 48 && c <= 57)//判断数字字符
(* num)++;
else if (c == '\n')//判断换行符
(* row)++;
else//判断其他字符
(* other)++;
}
(* other)--;
}
int main()
{
FILE* pfile;
if ((pfile = fopen("a.txt", "r")) == NULL)
{
printf("文件打开失败!\n");
exit(0);
}
int row = 0, capital = 0, small = 0, num = 0, other = 0;
countFile(pfile, &row, &capital, &small, &num, &other);//调用函数
printf("文件行数:%d\n", row);
printf("大写字母个数:%d\n", capital);
printf("小写字母个数:%d\n", small);
printf("数字字符个数:%d\n", num);
printf("其他字符个数:%d\n", other);
if (fclose(pfile))
{
printf("不能正常关闭文件!\n");
exit(0);
}
return 0;
}
三、运行结果
别问今天为什么不讲故事,问就是作者和这段代码没有什么特别的故事(摊手无奈表情)
还有一件事就是作者最近太忙啦!