Here is a Simple Shell Program In C Language which counts the number of chars, words, and Lines Provided in the input.
#include <stdio.h>
#include <conio.h>
void count();
void main(int argc, char *argv[])
{
char fname[20];
char option;
if( argc != 3 )
{
printf("Invalid number of arguments");
return ;
}
option = *argv[1];
strcpy(fname,argv[2]);
count(fname, option);
} // main
void count( char fname[], char option)
{
long ccnt, wcnt,lcnt;
FILE *fp;
long lflag,wflag;
int ch;
fp = fopen(fname,"r");
if( fp == NULL )
{
printf("\nUnable to open a file");
exit(0);
}
ccnt = wcnt = lcnt = 0;
lflag = wflag = 1;
ch = fgetc(fp);
while( ch != EOF )
{
ccnt++;
if( ch == ' ' || ch == '\t')
{
lflag = 0;
if( wflag == 0 )
{
wcnt++;
wflag = 1;
}
}
else
if( ch == 10 )
{
ccnt++;
lcnt++;
lflag = 1;
if( wflag == 0 )
{
wcnt++;
wflag = 1;
}
}
else // normal
{
wflag = 0;
lflag = 0;
}
ch = fgetc(fp);
} // while
if( wflag == 0 )
wcnt++;
if( lflag == 0 )
lcnt++;
switch(option)
{
case 'c' :printf("\n char count = %ld\n",ccnt);
break;
case 'w' :
printf("\n word count = %ld\n",wcnt);
break;
case 'l' :
printf("\n line count = %ld\n",lcnt);
} // switch
} // count
#include <stdio.h>
#include <conio.h>
void count();
void main(int argc, char *argv[])
{
char fname[20];
char option;
if( argc != 3 )
{
printf("Invalid number of arguments");
return ;
}
option = *argv[1];
strcpy(fname,argv[2]);
count(fname, option);
} // main
void count( char fname[], char option)
{
long ccnt, wcnt,lcnt;
FILE *fp;
long lflag,wflag;
int ch;
fp = fopen(fname,"r");
if( fp == NULL )
{
printf("\nUnable to open a file");
exit(0);
}
ccnt = wcnt = lcnt = 0;
lflag = wflag = 1;
ch = fgetc(fp);
while( ch != EOF )
{
ccnt++;
if( ch == ' ' || ch == '\t')
{
lflag = 0;
if( wflag == 0 )
{
wcnt++;
wflag = 1;
}
}
else
if( ch == 10 )
{
ccnt++;
lcnt++;
lflag = 1;
if( wflag == 0 )
{
wcnt++;
wflag = 1;
}
}
else // normal
{
wflag = 0;
lflag = 0;
}
ch = fgetc(fp);
} // while
if( wflag == 0 )
wcnt++;
if( lflag == 0 )
lcnt++;
switch(option)
{
case 'c' :printf("\n char count = %ld\n",ccnt);
break;
case 'w' :
printf("\n word count = %ld\n",wcnt);
break;
case 'l' :
printf("\n line count = %ld\n",lcnt);
} // switch
} // count
No comments:
Post a Comment