#include <stdio.h>
#include <stdlib.h>
/*
统计文件内容行数、单词数、字符数
格式:可执行文件名 -l -w -c 数据文件列表
*/
int main(int argc, char* argv[])
{
FILE* fp;
int lflag, wflag, cflag; //l w c 3个标志
int line, word; //行内与单词内标志
int lcount, wcount, ccount; //统计变量
char *s;
int c;
if (argc < 2) //参数个数不够
{
printf ("argc error\n");
exit(1);
}
lflag = wflag = cflag = 0;
lcount = wcount = ccount = 0;
while (--argc >= 1 && (*++argv)[0] == '-') //解析参数
{
for (s = argv[0] + 1; *s; ++s)
{
switch (*s)
{
case 'l': //-l参数
lflag = 1;
break;
case 'w': //-w参数
wflag = 1;
break;
case 'c': //-c参数
cflag = 1;
break;
default: //参数不对
printf ("To run this program, usage: program -l -w -c file1 file2 ... filen\n");
exit(1);
}
}
}
if (argc == 0) //参数列表中没有数据文件
{
printf ("To run this program, usage: program -l -w -c file1 file2 ... filen\n");
exit(1);
}
if (lflag == 0 && wflag == 0 && cflag == 0) //默认情况下,统计行数、单词数、字符数
lflag = wflag = cflag = 1;
while (--argc >= 0)
{
if ((fp = fopen(*argv, "r")) == NULL)
{
fprintf (stderr, "Can't open %s file\n", *argv); //在标准错误流下打印出错信息
continue;
}
line = word = 0; //初始化标志
while ((c = fgetc(fp)) != EOF) //逐个字符读取,统计行数或单词数或字符数
{
if (cflag)
++ccount;
if (wflag)
{
if (c == '\n' || c == ' ' || c == '\t')
word = 0;
else if (word == 0)
{
++wcount;
word = 1;
}
}
if (lflag)
{
if (c == '\n')
line = 0;
else if (line == 0)
{
++lcount;
line = 1;
}
}
}
if (lflag)
printf ("%s file Lines = %d\n", *argv, lcount);
if (wflag)
printf ("%s file Words = %d\n", *argv, wcount);
if (cflag)
printf ("%s file Chars = %d\n", *argv, ccount);
fclose(fp);
++argv; //统计下一个数据文件
lcount = wcount = ccount = 0;
}
system("PAUSE");
return 0;
}