In: Computer Science
Write a C program that counts the number of non white-space characters in an inputtext file. Program takes as command argument(s)the name of the input file (and the output file with option -f). Based on the option flags, it displays the output on the standard output, or writesthe output to an output file.
The command format is as follows:
command -f inputfile outputfile
or,
command -s inputfile
-f indicates writing to an output file;
-s indicates displaying the output on the screen.
Also notice the errors caused by incomplete arguments.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char ** argv)
{
FILE *file=NULL;char ch;
int count_char=0;
file=fopen(argv[2],"r");
if(!file){
printf("error while opening the file\n");exit(0);}
while( (ch = getc(file))!= EOF)
{
if(ch!=' ')
count_char++;
}
fclose(file);
if(argv[1][0]=='s')
{
printf("Total number of non space characters in a file is =
%d\n",count_char);
}
else if(argv[1][0]=='f')
{
FILE * file1;
file1=fopen(argv[3],"w");
if(file1){
fprintf(file1,"%s %d", "Total number of non space characters in a
file is =", count_char);
fclose(file1);}
else
printf("unable to write into file\n");
}
}