第二个项目:Word Count
一、主要功能:文件中字符数、单词数、行数的统计
二、github源码和工程文件地址:https://github.com/miniyuan222/the-second
三、代码展示:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int readData(char filename[]);
void writeData(int n, int x);
int hanzi(char filename[]);
void main(void)
{
char name[40] = "H:\\1.txt";
int word_num;
int hanzi_num;
word_num = readData(name);
hanzi_num = hanzi(name);
writeData(word_num, hanzi_num);
system("pause");
}
int readData(char filename[]) //此函数计算英文单词个数
{
FILE* fp;
char ch;
char flag = 0;
int num = 0;
if ((fp = fopen(filename, "r")) == NULL)
{
printf("%s open failure", filename);
exit(EXIT_FAILURE);
}
printf("%s open sucessfully!~\n", filename);
while (!feof(fp))
{
ch = fgetc(fp);
//(ch < 0x80) 排除汉字的干扰
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'))
flag = 0;
else if (flag == 0 && (ch != '-' && ch != '/'&& ch != '\''))
{
num++;
flag = 1;
}
}
fclose(fp);
return num;
}
int hanzi(char filename[]) //此文件计算汉字个数
{
FILE* fp;
int ch; //注意这里是int型的
int count = 0;
if ((fp = fopen(filename, "r")) == NULL)
{
printf("%s open failure.\n", filename);
exit(EXIT_FAILURE);
}
while (!feof(fp))
{
ch = fgetc(fp);
if (ch == -1)
break;
if (ch >= 0x80)
{
count++;
ch = fgetc(fp);//为什么要再来一次? 哦 因为fgetc每次只能取到一个字节 汉字是两个字节(可能是为了废掉一个字节)
}
}
fclose(fp);
return count;
}
void writeData(int n, int x) //此文件输出
{
FILE* fp;
if ((fp = fopen("D:\\result.txt", "a")) == NULL)
{
printf("File open failure!!!");
exit(EXIT_FAILURE);
}
fprintf(fp, "文件中的单词个数为%d\n", n);
fprintf(fp, "文件中的汉字个数为%d\n", x);
printf("文件中的单词个数为%d\n", n);
printf("文件中的汉字个数为%d\n", x);
printf("结果保存在D:\\result.txt当中\n");
fclose(fp);
}
四、总结:代码借鉴网上分享,并且与同学相互交流修改,增加了一个可以将统计结果保存到原文件里的功能,最后完成了该小项目。