Question

In: Computer Science

Nearby is a main() function demonstrating the use of the function earliest_word. Implement this function according...

Nearby is a main() function demonstrating the use of the function earliest_word. Implement this function according to the documentation given. My solution is about 25 lines plus some closing curly braces.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

char *earliest_word(char *fname, int *nwords);

// Opens the file fname and reads words from it

// until the end of file is reached then closes

// the file. If the file to be opened doesn't

// exist, returns NULL and sets nwords to

// -1. Tracks the alphabetic "earliest" word that

// is read in as indicated by strcmp(). Tracks how

// many words in total are read and sets nwords to

// that value. Allocates a block of memory and

// copies the earliest word found into the block

// using strcpy(). Returns a pointer to the

// freshly allocated block.

//

// ASSUMPTIONS: Words are no longer than 127

// characters so will fit in an array of size

// 128. Files have at least one word in them.

int main(){

int count; char *file; char *early;

file = "vegetables.txt";

// pumpkin carrot beet squash cucumber

early = earliest_word(file, &count);

printf("%s: %d words, %s earliest\n",

   file,count,early);

// vegetables.txt: 5 words, beet earliest

free(early);

file = "fruits.txt";

// banana peach orange apple pineapple strawberry

early = earliest_word(file, &count);

printf("%s: %d words, %s earliest\n",

   file,count,early);

// fruits.txt: 6 words, apple earliest

free(early);

file = "not-there.txt";

early = earliest_word(file, &count);

if(early==NULL){

printf("%s not found\n",file);

// not-there.txt not found

}

return 0;

}

C programming

Solutions

Expert Solution

#include <stdio.h>
#include <stdlib.h>
/**
 * Global variables
 */
FILE *fileToRead;
char ch;
int num_characters, nwords, num_lines;

void earliest_word(char *fname, int nwords) {
    fileToRead = fopen(fname, "r");

    /* Check if the file is opened*/
    if (fileToRead == NULL) {
        printf("Problem occurred will trying to open the file.\nCheck if the file exists or provide the right path\n");
        // set file nwords to negative one
        nwords = -1;
        exit(EXIT_FAILURE);
    }

    /*
     * Logic to count num_characters, nwords and num_lines.
     */
    num_characters = nwords = num_lines = 0;
    while ((ch = fgetc(fileToRead)) != EOF) {
        num_characters++;

        /* new line checker*/
        if (ch == '\n' || ch == '\0')
            num_lines++;

        /* Words checker */
        if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
            nwords++;
    }

    /* Increment nwords and num_lines for last word */
    if (num_characters > 0) {
        nwords++;
        num_lines++;
    }

    /* Print fileToRead statistics */
    printf("\nTotal num_lines in the file  = %d\n", num_lines);
    printf("Total number of words in the file      = %d\n", nwords);
    printf("Total number of characters in in the file = %d\n", num_characters);

    /* Closing the file after read completion*/
    fclose(fileToRead);
}

// main function
void main() {
    // file to read pointer declaration
    FILE *fileToRead;
    //character array of file filePath to read
    char * filePath[100];
    //file entry
    printf("Please provide the source filePath: ");
    scanf("%s", filePath);

    /* Open the fileToRead in read mode */
    fileToRead = fopen(filePath, "r");
    //operation process
    //External method call
    earliest_word(filePath,nwords);
}
OutPut:

_________________________________

Comment Down For Any Queries.

Please Give a Thumbs Up If You are satisfied With The Answer.


Related Solutions

Complete the function main in file median.c to implement the computation of the median of a...
Complete the function main in file median.c to implement the computation of the median of a sequence of integers read from stdin. The program should use realloc to allow an arbitrary number of integers to be read into a dynamically allocated array. Every time realloc is called, let the new size of the array be twice the old size plus 1. Look at function readLongLine in the slides for Chapter 6 for an example of how to use realloc. The...
Write a recursive function to implement the Factorial of n (n!). In the main, let the...
Write a recursive function to implement the Factorial of n (n!). In the main, let the user input a positive integer and call your function to return the result.
Use on 4-to-1 MUX to implement the majority function
Use on 4-to-1 MUX to implement the majority function
Implement each of the following functions and write a basic main() function that tests each. For...
Implement each of the following functions and write a basic main() function that tests each. For convenience, you should be able to find this starter class under Mimir's assignment 4 starter code. Do not change the name, parameters, or returns of any of these functions or of the name of the class itself. There is also no need in this assignment for any global variables. You are strongly encouraged to use your solution for some of these functions in others...
List the three main goals of a project. Use an example of a project to implement...
List the three main goals of a project. Use an example of a project to implement a new billing procedure for a small lawn mowing business, describe how project management principles help achieve these goals.
Discuss concepts associated with mercantilism demonstrating key policies that a country would implement if they were...
Discuss concepts associated with mercantilism demonstrating key policies that a country would implement if they were to apply such a theory. What is the liberal critique of mercantilism?
Use the Heap class provided to implement a sort routine in a Main class where the...
Use the Heap class provided to implement a sort routine in a Main class where the user enters a series of values, each value is then pushed onto a heap, then the values are printed out in ascending order. public class Heap { public static final int SIZE = 1025; public Heap() { elt = new Element[SIZE]; lastLoc = 0; } public void push(String k, Object o) { if (!fullCheck()) { lastLoc++; elt[lastLoc] = new Element(k,o); int loc = lastLoc;...
Please Use C++ to finish as the requirements. Implement a class called SinglyLinkedList. In the main...
Please Use C++ to finish as the requirements. Implement a class called SinglyLinkedList. In the main function, instantiate the SinglyLinkedList class. Your program should provide a user loop and a menu so that the user can access all the operators provided by the SinglyLinkedList class. DestroyList InitializeList GetFirst InsertFirst, InsertLast, Insert DeleteFirst, DeleteLast, Delete IsEmpty Length Print, ReversePrint
Implement a non-recursive reverse print of linked list using stack and the main function to test:...
Implement a non-recursive reverse print of linked list using stack and the main function to test: You will need to finish the printReversed_nonrecursive method in ch04.LinkedStack2 class, and the ch04.UseStack2 is the main function to test. public class LinkedStack2<T> extends LinkedStack<T> { private void revPrint(LLNode<T> listRef) { if (listRef != null) { revPrint(listRef.getLink()); System.out.println(" " + listRef.getInfo()); } } public void printReversed() { revPrint(top); } /* use stack to implement non-recursive reverse print */ public void printReversed_nonrecursive() { } public...
/*Use recursion in the function: void getDigit( int num) /* Try this program and implement the...
/*Use recursion in the function: void getDigit( int num) /* Try this program and implement the function void getDigit( intnum) so that it displays the digits in a given number. For example, the number, 1234 consist of 1, 2, 3 and 4. This is an exercise to demonstate the use of a recursive function and the use of recusrion in C++ */ #include #include using namespace std; int main() {      int num;      cout <<"Enter an integer: ";     ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT