Write a C program named “mywc.c” simulating the “wc” command taking some options
ID: 3768872 • Letter: W
Question
Write a C program named “mywc.c” simulating the “wc” command taking some options and text file as arguments. If no option is given, mywc outputs the number of lines, words and characters in the given file as well as the file name separated by a blank space. When the –l option is used, mywc can output the number of lines; When the –w option is used, mywc can output the number of words; When the –c option is used, mywc can output the number of characters. Also if -lc is given then it should return # of lines and characters, if -lw them return # of lines and words and if -wc then # of words and characters If the given file doesn’t exist, it gives an error message with program name, text file name and the causal separated by colon. The program should also meet the following requirements. (1) Use structure to store the number of lines, words, and characters. (2) Characters only include letters and digits. (3) The order of options does not matter. (4) When take the screenshot, always show the text first. The output could be like this.
Explanation / Answer
#include #include int main() { FILE *fp; char buff[255]; char command[255]; int c=0,i,j=0; int line=0; int word=0; char ch; char fileName[255]; printf("********************************************* "); printf("Enter command (Example -c input.txt) "); printf("-c for Number of character in file "); printf("-w for Number of words in file "); printf("-l for Number of lines in file "); printf("********************************************* "); scanf("%s",command); //Extracting file name if(command[2]==' ') { if(command[1]=='l' || command[1]=='w' || command[1]=='c') { while(command[i]!='') { if(i>2) { fileName[j]=command[i]; i++; } fileName[i]=''; } printf("********************************************* "); printf("File Name You have provided is:%s ",fileName); printf("********************************************* "); fp = fopen(fileName, "r"); if(fp) { while(!feof(fp )) { memset(buff, '', sizeof( buff) ); fgets(buff, 255, (FILE*)fp); for(i = 0; buff[ i ]; i++) { if (buff[i] == ' ') line ++,word++; else if (buff[i] == ' ') word ++; else c++; } } fclose(fp); if(command[0]=='-' && command[1]=='w') printf("Number of words in file: %i ", word); else if(command[0]=='-' && command[1]=='c') printf("Number of characters in file: %i ",(c-2)); else if(command[0]=='-' && command[1]=='l') printf("Number of lines in file: %i ", line); else { printf("Number of words in file: %i ", word); printf("Number of characters in file: %i ",(c-2)); printf("Number of lines in file: %i ", line); } printf("********************************************* "); } else printf("File not found"); return; }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.