运行效果:
/* 英文注释的也许不对, 自己看嘛, 我懂就行了......
* 有问题, 欢迎讨论 1005411480a@gmail.com
*/
/*
* swc - Count lines, words and characters in a file(or many) or characters from stdin
* the same function with wc
*
* Author: Zhigang Song <1005411480a@gmail.com>
* Last modified: Mar. 23th, 2013
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define IN 1
#define OUT 0
int wflag; /* flag to count words */
int lflag; /* flag to count lines */
int cflag; /* flag to count characters */
int nlines; /* number of lines in a file */
long int nwords; /* number of words in a file */
long int nchars; /* number of characters in a file */
int ltotal; /* number of total lines */
long int wtotal; /* number of total words */
long int ctotal; /* number of total characters */
int main(int argc, char **argv)
{
FILE *fp;
int onemorefile = argc;
int opt_arg_num;
void deal_with_argv(int *, char **argv);
void count(FILE *);
if(argc > 1)
deal_with_argv(&opt_arg_num, argv); /* process the command line arguments */
if(!wflag && !lflag && !cflag){ /* count words, lines and characters by default */
wflag = lflag = cflag = 1;
}
argv += opt_arg_num + 1;
argc -= opt_arg_num + 1;
onemorefile = argc;
while(argc-- > 0){ /* get input from file */
fclose(stdin);
if((fp = fopen(*argv, "r")) == NULL){
fprintf(stderr, "Error: cannot open file %s\n", *argv);
exit(1);
}else{
count(fp);
if(wflag) printf(" %6d", nwords);
if(cflag) printf(" %6d", nchars);
if(lflag) printf(" %6d", nlines);
printf("\t%s\n", *argv);
fflush(stdout);
argv++;
}
}
if(!onemorefile){ /* get input from stdio but not a file */
count(stdin);
if(lflag) printf(" %6d", nlines);
if(wflag) printf(" %6d", nwords);
if(cflag) printf(" %6d", nchars);
fflush(stdout);
exit(0);
}else if(onemorefile > 1){
if(wflag) printf(" %6d", wtotal);
if(cflag) printf(" %6d", ctotal);
if(lflag) printf(" %6d", ltotal);
printf("\ttotal\n" );
fflush(stdout);
}
return 0;
}
void deal_with_argv(int *opt_arg_num, char **argv)
{
char c;
void usage(void);
*opt_arg_num = 0;
while(**++argv == '-'){
(*opt_arg_num)++;
while((c = *++*argv) != '\0'){
switch(c){
case 'l':
lflag = 1;
break;
case 'w':
wflag = 1;
break;
case 'c':
cflag = 1;
break;
default:
usage();
break;
}
}
}
}
void usage(void)
{
fprintf(stderr, "Usage: swc -[lwc] filenamea filenameb ...\n");
exit(3);
}
void count(FILE *fp)
{
register char c;
register char state;
nchars = nwords = nlines = 0;
while((c = getc(fp)) != EOF){
nchars++;
if(!isspace(c))
state = IN;
else{
if(state)
nwords++;
state = OUT;
}
if(c == '\n' || c == '\f')
nlines++;
}
wtotal += nwords;
ltotal += nlines;
ctotal += nchars;
}