Question
How do I change this code so that I can type mywords -c -f 'he' testfile.txt on the command line and it state that it
How do I change this code so that I can type mywords -c -f 'he' testfile.txt on the command line and it state that it found 'he' within 'here' which is included in the testfile.txt.
#include #include #include //Declare constants #define n 10000 #define OUT 0 #define IN 1 //Implement method countWords() unsigned countWords(char *str) { //declare local variables int state = OUT; unsigned wc = 0; while (*str) { if (*str == ' ' || *str == ' ' || *str == ' ') { state = OUT; } else if (state == OUT) { state = IN; ++wc; } ++str; } return wc; } //Implement method all_words void all_words(char *str1, int num_words) { //Declare local variables int i, j, c = 0; char temp[50], *split_str, str[60][20]; split_str = strtok(str1, " ,.-"); //use while loop to read the string until null while (split_str != NULL) { strcpy(str[c], split_str); split_str = strtok(NULL, " ,.-"); c++; } for (i = 1; i0) { strcpy(temp, str[j - 1]); strcpy(str[j - 1], str[j]); strcpy(str[j], temp); } } } //sort the words printf(" Sorted Order "); for (i = 0; i 0) { printf(" '%s' appears %d time(s) ", word, times); } else { printf(" '%s' does not appear in the sentence. ", word); } } //main method int main(int argc, char *argv[]) { int opt; //Declare local variables char buff[n], search_str[100]; FILE *file; size_t nread; int i, num_of_words; //open the file file = fopen(argv[5], "r"); //If file if (file) { //print the file content printf("File Content... "); while ((nread = fread(buff, 1, sizeof buff, file)) > 0) fwrite(buff, 1, nread, stdout); if (ferror(file)) { //print error printf("Error...."); } fclose(file); } //use while loop to read the parameters while ((opt = getopt(argc, argv, ":-f:cs")) != -1) { switch (opt) { //if command option is c //call the method to count number of words case 'c': num_of_words = countWords(buff); printf(" Number of words-->>%d ", num_of_words); break; //if command option is f //call the method to search occurence of words case 'f': printf("substring: %s ", optarg); search_occ(optarg, buff); break; //if command option is s //call the method to sort number of words case 's': all_words(buff, num_of_words); break; //if command option is : //call the method to sort number of words case ':': printf("option needs a value "); break; case '?': printf("unknown option: %c ", optopt); break; } } //return 0 return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started