C语言统计文件字符数 单词数 行数

  前天用java写了这个功能,今天用C语言实现了一下,有点恼火的就是判断每行字符串最后一个字符了,如果为空格的话就要特别处理一下,还要注意,记得每行时都要将

isLastBlank重置为1,而且刚刚开始时候他的值是为0.
github地址:https://github.com/ICanV/wc

看代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void wcexe(char *filename){
	FILE *fp;
	char buffer[1000];
	char c;
	int bufferlen;
	int isLastBlank = 0; // 上个字符是否是空格(1表示是  0表示不是)
	int charCount=0;
	int wordCount=0;
	int lineCount=0;
	int i;

	if((fp=fopen(filename,"rb"))==NULL){
		printf("文件不能打开\n");
		exit(0);
	}
	while(fgets(buffer,1000,fp)!=NULL){
		bufferlen=strlen(buffer);
		for(i=0;i<bufferlen;i++){
			c=buffer[i];
			if(c==' ' || c=='\t'){
				if(isLastBlank==0){
					wordCount++;
				}
				isLastBlank=1;
			}else if(c!='\n'&&c!='\r'){
				charCount++;
				isLastBlank=0;
			}

		}
		if(isLastBlank==0)
			wordCount++;
		isLastBlank=1;
		lineCount++;
	}
	fclose(fp);
	printf("行数:%d\n",lineCount);
	printf("字符数:%d\n",charCount);
	printf("单词数:%d\n",wordCount);

	
}
void main(){
	char filename[]="C://Users//Administrator//Desktop//123.txt";
	wcexe(filename);

  

  

转载于:https://www.cnblogs.com/liupeixuan/p/7551016.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值