作业2:wordcount项目

这次的项目是做一个类似于shell命令wc的项目,我在博客上找了一个比较好的代码,网址是http://www.cnblogs.com/sunbuqiao/p/5312227.html。代码:

#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 ", 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]) != ''; i++)
{
if (c == ' ')//判断字符中单词数
{
num2++;
word = OUT;
}
else
{
if (word == OUT)
{
word = IN;
num1++;
}
}
if ((c = str[i]) == ' ')
{
num4++;
}
}
num3 = length - num2-num4*2;//字符数
num4++;//行数
fclose(fp);
printf("空格数为%d ", num2);
printf("单词数为%d 行数为%d 字符数为%d ", num1, num4, num3);
system("pause");

}

原文地址:https://www.cnblogs.com/tzk971118/p/7613098.html