前天用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);