wordcount程序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<windows.h>
#define IN 1
#define OUT 0
void main() {
FILE *fp;
int length;
fp = fopen("wang.txt","r");//打開要計數的文件
if (fp == NULL)
{
printf("can not open file");
exit(0);
}
fseek(fp, 00, SEEK_END);
length = ftell(fp);
printf("%d\n", length);//確定所要查找的文件中總字符數長度,並在屏幕中顯示出來
rewind(fp);
char str[100000], c;
fread(str, sizeof(char), length, fp);//從文件中讀取所有的字符到str序列
int i, num1 = 0, num2 = 0, num3, num4=0, word = OUT;
for (i = 0; (c = str[i]) != ‘\0‘; i++)
{
if (c == ‘ ‘)//判斷字符中單詞數
{
num2++;
word = OUT;
}
else
{
if (word == OUT)
{
word = IN;
num1++;
}
}
if ((c = str[i]) == ‘\n‘)
{
num4++;
}
}
num3 = length - num2-num4*2;//字符數
num4++;//行數
fclose(fp);
printf("空格數為%d\n", num2);
printf("單詞數為%d\n行數為%d\n字符數為%d\n", num1, num4, num3);
system("pause");
}
from http://www.cnblogs.com/sunbuqiao/p/5312227.html
wordcount程序