Write a C program named “mywc.c” simulating the “wc” command taking some options
ID: 665841 • Letter: W
Question
Write a C program named “mywc.c” simulating the “wc” command taking some options and text file as arguments. If no options are given, mywc outputs the number of lines, words and characters in the given file as well as the file name separated by 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. If the given file doesn’t exist, it gives an error message with program name, text file name and the casual separated by colon. Below are sample runs of mywc(assuming mywc is the generated executable file):
$./mywc test.txt
2 5 8 test.txt
$./mywc –l test.txt
2
$./mywc –w test.txt
5
$./mywc –c test.txt
8
$./mywc –lw test.txt
2 5
$./mywc –lc test.txt
2 8
$./mywc –lwc test.txt
2 5 8
$./mywc nonexist.txt
./mywc:nonsexist.txt: No such file or directory
Explanation / Answer
#include #include #include int main(int argc, char** argv) { int bytes = 0; int words = 0; int newLine = 0; char buffer[1]; enum states { WHITESPACE, WORD }; int state = WHITESPACE; if ( argc !=2 ) { printf( "Help: %s filename", argv[0]); } else{ FILE *file = fopen( argv[1], "r"); if(file == 0){ printf("can not find :%s ",argv[1]); } else{ char *thefile = argv[1]; char last = ' '; while (read(thefile,buffer,1) ==1 ) { bytes++; if ( buffer[0]== ' ' || buffer[0] == ' ' ) { state = WHITESPACE; } else if (buffer[0]==' ') { newLine++; state = WHITESPACE; } else { if ( state == WHITESPACE ) { words++; } state = WORD; } last = buffer[0]; } printf("%d %d %d %s ",newLine,words,bytes,thefile); } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.