#include"count_text.h"
#include <stdio.h>
#include<windows.h>
int main(int argc,char* argv[])
{
char* file = NULL;
FILE* fp = NULL;//文件指针,指向file文件
fp = fopen(argv[1], "rb");//只读
fseek(fp, 0L, SEEK_END);//定位到文件末尾
int size = ftell(fp);//从文件开始到末尾的的字节数
file = (char*)malloc(size+1);
memset(file, 0, size+1);
strcpy(file, argv[1]);
fp = fopen(file, "rb");//只读
if (fp == NULL)
{
fprintf(stderr, "can't open file.txt\n");
return(EXIT_FAILURE);
}
/*char ch = 0;
while (EOF != (ch = getc(fp)))
{
printf("%c", ch);
}
*/
//统计字符数
count_ch(fp);
//统计单词数
count_word(fp);
//统计行数
count_lines(fp);
//统计非空行数
count_non_empty_line(fp);
fclose(fp);
free(file);
file = NULL;
system("pause");
return(0);
}
#ifndef COUNT_TEXT_H
#define COUNT_TEXT_H
#include <stdio.h>
int count_ch(FILE* fp);
int count_word(FILE* fp);
int count_lines(FILE* fp);
int count_non_empty_line(FILE* fp);
#endif
#include"count_text.h"
#include <stdio.h>
#include<ctype.h>
//#define SPACE ' '
//#define NON ('\n'!= (ch = getc(fp)))&&('\r'!= (ch = getc(fp)))&& ('!' != (ch = getc(fp))) && ('\t' != (ch = getc(fp)))&& (',' != (ch = getc(fp))) && ('*' != (ch = getc(fp)))
int count_ch(FILE* fp)
{
char ch = 0;
int count_ch = 0;
rewind(fp);//返回文件开始处
while (EOF != (ch = getc(fp)))
{
++count_ch;
}
printf("文本中的字符数为:%d\n", count_ch);
return count_ch;
}
int count_word(FILE* fp)
{
int count_word = 0;
char ch = 0;
int flag = 0;
rewind(fp);
ch = getc(fp);
while (EOF != ch)
{
//如果不是空白字符,就是标志单词的开始
//if ((ch != ' ') && ('!' != ch) && ('*' != ch) && ('\r' != ch) && ('\n' != ch))
if (isalnum(ch))
{
if (flag == 0)
{
flag = 1;//标记单词
}
}
//如果是空白字符,再次判断是不是单词状态(排除多个连续空白字符,误被统计成单词)
else
{
if (flag == 1)
{
++count_word;
flag = 0;
}
}
ch = getc(fp);
}
//判断最后一个非空白字符的单词
if (flag == 1)
{
++count_word;
}
printf("the count of word is:%d\n", count_word);
return count_word;
}
int count_lines(FILE* fp)
{
int count_line = 0;
char ch = 0;
rewind(fp);
ch = getc(fp);
while (EOF != ch)
{
if (ch == '\n')
{
++count_line;
}
ch = getc(fp);
}
printf("the count of line:%d\n", count_line);
return count_line;
}
int count_non_empty_line(FILE* fp)
{
int count_non_empty_line = 0;
int count_empty_line = 0;
char ch = 0;
rewind(fp);
while (EOF != ch)
{
if ((ch == '\n') && ((ch = getc(fp)) == '\r'))
{
++count_empty_line;
}
ch = getc(fp);
}
int count=count_lines(fp);
count_non_empty_line = count - count_empty_line;
printf("the count of non_empty_line: %d\n", count_non_empty_line);
return count_non_empty_line;
}
a this is book
c standard library
library functions and macros
end