Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C program that counts the number of non white-space characters in an inp

ID: 3789630 • Letter: W

Question

Write a C program that counts the number of non white-space characters in an input text 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 writes the 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

Explanation / Answer

Answer:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

int count = 0;
if( argc == 3 ) {
if(strcmp(argv[1],"-s") == 0) {
printf("Printing the count in command line ");
} else {
printf("Incomplete arguments ");
exit(1);
}
} else if(argc == 4) {
if(strcmp(argv[1],"-f") == 0) {
printf("Printing the count in output file: %s ",argv[3]);
} else {
printf("Incomplete arguments ");
exit(1);
}
}else {
printf("Incomplete arguments ");
exit(1);
}

/* file handle --- in this case I am parsing this source code */
FILE *fp = fopen(argv[2], "r");

/* a holder for each character (stored as int) */
int c;

/* for as long as we can get characters... */
while((c=fgetc(fp))) {

/* break if end of file */
if(c == EOF) break;

/* otherwise add one to the count of that particular character */
if(c != ' '){
count+=1;   
}
}

if(strcmp(argv[1],"-f") == 0) {
FILE *o = fopen(argv[3], "w");
if (o == NULL)
{
printf("Error opening file! ");
exit(1);
}
  
/* print some text */
fprintf(o, "Count of non-space characters: %d ", count);
fclose(o);
} else {
/* now print the results; only if the count is different from
* zero */
printf("%d times ", count);
}
/* close the file */
fclose(fp);
}

Comment : Added the comments then and there in the code itself. All the best.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote