Question

In: Computer Science

only using C (not C++) Implement a program that counts the words and prints their frequencies....

only using C (not C++)

Implement a program that counts the words and prints their frequencies. In particular, the program extracts “words” from one or more text files, from a pipe, or from the console, and prints to the console the list of words found and their associated frequencies. Note that your project submission is restricted to only using the following system calls: open(), close(), read(), write(), and lseek() for performing I/O. You are allowed to use other C library calls (e.g., malloc(), free()), however, all I/O is restricted to the Linux kernel’s direct API support for I/O.

There are three ways the list of words is provided to your program:

  1. In a list of one or more files. The names of the files are provided as arguments to your program (i.e., they are copied by the shell in the argv variable), and each file is a text file with lots of words.

  2. The words are provided to stdin either by piping or by user input.

  3. An environment variable, WORD_FREAK, is set with the name of the file containing the words.

We’ll focus on one of these ways, namely, getting the input from a file. Let’s assume the words are provided in one file, passed as an argument to your program (i.e., option 1). A sample text file (for this use any text file with thousands of words) is (not) provided. Given the constraint of using Linux API for I/O, complete the following:

  1. Open the manual page for open() system call and add to your code the header files required to use open(), using the include preprocessor statement.

  2. Use the open() system call to open the file passed to your program in argv[1] for reading. What flag should you pass to open(), to open the file in read-only mode?

  3. Open the manual page for read() system call and add to your code the header files needed for read().

  4. Use the read() system call to read the characters from the file. What parameters does read() take, and what value does it return? Repeat, if necessary the call to read() until all characters are read from the input file.

  5. Use printf() to output to the terminal the text just read from the input file. Note that for the project you are not allowed to use printf(). However, while debugging your code, it can be used to confirm the correct reading of the file contents.

  6. Open the manual page for close() system call and determine which header file you should include in your code to call close().

  7. Use the close() system call to close the file.

Solutions

Expert Solution

C++ Code:-

#include <iostream>
#include <string.h>
#include <fstream>

using namespace std;

//structure defintion
struct WordCount
{
   //two data members
   char word[31];
   int count;
};


//Function to convert string upper case
void stringToUpper(char *s)
{
   for(int i=0;s[i]!='\0';i++) //repeat until end of string char null
   {
       if(*(s+i)>=97 && *(s+i)<=122) //when lower case letter
           *(s+i)=*(s+i)-32;//convert to upper case by subtraction of ascii with 32
   }
}

//Function striping punctuation characters
void stripPunctuation(char *s)
{
   int pos=0;
   for (char *p = s; *p; ++p) //repeat all characters
       if (isalpha(*p)) //when alphabet
           s[pos++] = *p; //then concate to s
   s[pos] = '\0'; //end with null
}
          

//Function search word
int searchForWord(const char* word, const WordCount wordArray[],int numWords)
{
   for(int i=0;i<numWords;i++) //repeat loop
       if(strcmp(wordArray[i].word,word)==0) //when matched
           return i;//return its index
   return -1;//return -1, when fails
}

//Function for counting words
int countWords(const char* fileName,WordCount wordArray[])
{
   ifstream infile(fileName);//open file for reading
   int count=0;//initially count is 0
   char word[31];//take max length word
   infile>>word;//read the word
  
   while(!infile.eof()) //repeat until end of file
   {
       stringToUpper(word);//convert to upper case
       stripPunctuation(word);//remove punctuation characters
       int found=searchForWord(word, wordArray,count);//search word
       if(found==-1) //when not found
       {
           strcpy(wordArray[count].word,word);//store as new word
           wordArray[count].count=1;//first count is 1
           count++;//increment count
       }
       else //when found
           wordArray[found].count+=1;//increment existing count
       infile>>word;//read the next words
   }
   infile.close();//close the file
   return count;//finally return count      
      
}

//Function to sort words
void sortWords(WordCount wordArray[],int numWords)
{
   for(int i=0;i<numWords-1;i++) //outer loop
       for(int j=0;j<numWords-i-1;j++) //inner loop
       {
           if(strcmp(wordArray[j].word,wordArray[j+1].word)==0) //compare
           {
               //swapping process
               WordCount temp=wordArray[j];
               wordArray[j]=wordArray[j+1];
               wordArray[j+1]=temp;
           }
       }
}

//Function prints all words and their frequency
void printWords(const WordCount wordArray[],int numWords)
{
   cout<<"Word\tFrequency"<<endl;
   for(int i=0;i<numWords;i++) //repeat loop
   {
       cout<<wordArray[i].word<<"\t"<<wordArray[i].count<<endl;
   }
}
          

//main with command line arguments
int main(int argc,char* argv[])
{
   WordCount wordcount[200];//declare maximum 200 words
   if(argc!=2) //when count of args are not 2
   {
       cout<<"\nUsage : assign [file-name]"<<endl;//print error message
       return 1; //return error code 1
   }
   else //when passed exactly two args
   {
       int total=countWords(argv[1],wordcount);//read to array
       printWords(wordcount,total);//call print function
   }
      
   return 0;
}

//Sample.txt

I would love to try or hear the sample audio your app can produce. I do not want to purchase because I've purchased so many apps that say they do something and do not deliver,

Can you please add audio samples with text you've converted? I'd love to see the end results.

Thanks!

Output:-

Thank You....!!!!
For any query, please comment.
If you are satisfied by the above answer, then please thumbs up or upvote the answer.


Related Solutions

Write a C++ program that prints a calendar for a given year. ONLY USING "#include<iostream>" and...
Write a C++ program that prints a calendar for a given year. ONLY USING "#include<iostream>" and "#include<cmath>" The program prompts the user for two inputs:       1) The year for which you are generating the calendar.       2) The day of the week that January first is on, you will use the following notation to set the day of the week:       0 Sunday                     1 Monday                   2 Tuesday                   3 Wednesday       4 Thursday                 5 Friday                      6 Saturday Your program should...
Write a C++ program (using pointers and dynamic memory allocation only) to implement the following functions...
Write a C++ program (using pointers and dynamic memory allocation only) to implement the following functions and call it from the main function. (1)Write a function whose signature looks like (char*, char) which returns true if the 1st parameter cstring contains the 2nd parameter char, or false otherwise. (2)Create an array of Planets. Populate the array and print the contents of the array using the pointer notation instead of the subscripts.
I need a C++ program using while loops that counts the number of characters in a...
I need a C++ program using while loops that counts the number of characters in a sentence. The user inputs a sentence and then terminates the input with either '.' or '!'. And then it needs to count and display the number of a's, e's, i's, o's, u's, and consonants. The program should read both lower and upper case. They don't want us using switch statements or string operators, and want us to us if else if statements. I have...
in C++ For this program, you are going to implement a stack using an array and...
in C++ For this program, you are going to implement a stack using an array and dynamic memory allocation. A stack is a special type of data structure that takes in values (in our case integers) one at a time and processes them in a special order. Specifically, a stack is what's called a first-in-last-out (FILO) data structure. That is to say, the first integer inserted into the stack is the last value to be processed. The last value in...
Write a program in C++ that prints out the even numbers between 1 and 21 using...
Write a program in C++ that prints out the even numbers between 1 and 21 using WHILE loop. Also, find the sum AND product of these numbers and display the resulting sum and product.
C Program only - MUST USE MALLOC IN CODE Research and implement the Sieve of Eratosthenes....
C Program only - MUST USE MALLOC IN CODE Research and implement the Sieve of Eratosthenes. Example Program Session (implement some linefeed ‘\n’ formatting): Enter the limit: 1000 Primes up to 1000    2    3    5    7   11   13   17   19   23   29   31   37   41   43   47   53 59   61   67   71   73   79   83   89   97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211...
A program written in C that asks for the distance to be entered and then prints...
A program written in C that asks for the distance to be entered and then prints the fare A transportation company has the following rates For the first 100 miles                                                       20 cents a mile For the next 100 miles                                                       a) + 10 cents per mile over 100 miles For the next 100 miles                                                       b) + 8 cents per mile over 200 miles more than 300 miles                                                          c) + 5 cents per mile over 300 miles Write a program that asks...
Remember we're only using C to program this. That does not mean C++, just no! This...
Remember we're only using C to program this. That does not mean C++, just no! This one's long so pay attention. You are going to create a structure that resembles a university’s profile (Any university name is ok, just pick one). This structure must contain 5 members. They are listed here: 1. One member for number of undergraduate students 2. One member for number of graduate students 3. One member for number of classrooms 4. One member for the name...
Implement a program as an object using a class (abstract data type) in C++ that does...
Implement a program as an object using a class (abstract data type) in C++ that does the following: 1) reads the firstName, lastName and 3 test scores of at least five students. 2) calculate student test score totals, average, letter grade for each student. 3) Display the results in a table format showing firstName, lastName, test1, test2, test3, total, average, letterGrade, of all the students. 3 files .h, .cpp, main.cpp create an object that can hold records. must get records...
Write a C-program to implement the Reader/Writer model for the attached pseudocode modified to produce only...
Write a C-program to implement the Reader/Writer model for the attached pseudocode modified to produce only one million output instead of an infinite amount. Use pthreads and Linux semaphores. Include ten readers with one writer. The writer should produce one million outputs. Verify that the readers receive an equal share of the information produced. Meaning each reader receives about 100,000 of information. Explain your results regardless of the balance. No use mutex or monitor functions. ****PSEUDOCODE**** /* program readersandwriters */...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT