Question

In: Computer Science

Write a C program to run on unix to read a text file and print it...

Write a C program to run on unix to read a text file and print it to the display. It should count of the number of words in the file, find the number of occurrences of a substring, and take all the words in the string and sort them (ASCII order). You must use getopt to parse the command line. There is no user input while this program is running.

Usage: mywords [-cs] [-f substring] filename

• The -c flag means to count the number of words in the file. A word would be a series of characters separated by spaces or punctuation. A word could include a hyphen or a single apostrophe.

• The -s option means to print the words in the file sorted by ASCII order.

• The -f option will find the number of occurrences of the given substring.

• You may have any number of the flags included or none of them.

• The order they should be run would be: -s first, -c second, and -f third.

--------------------------------------------------------------------------------

Format of parsing the command line (main method established), rest of functionality needed as explained above:

int value = 0;

int main(int argc, char **argv) {
    extern char *optarg;
    extern int optind;
    int c, err = 0;
    int cflag = 0, sflag = 0, fflag = 0;
    char *substring;

    // usage 
    static char usage[] = "usage: mywords [-cs] [-f substring] filename";  

    while ((c = getopt(argc, argv, "csf:")) != -1)
        switch (c) {
            case 'c':
                cflag = 1;
                break;

            case 's':
                sflag = 1;
                break;

            case 'f':
                fflag = 1;
                substring = optarg;
                break;

            case '?':
                err = 1;
                break;
        }

    if (fflag == 1) {
        printf("%c ", substring);
    }
}

Solutions

Expert Solution

Updated Answer

Here we have written 4 functions :

1) printSortedWords

2)countWords

3) findSubString

4) readFile

for the various functionalities. Refer to the comments for the logic used. The main function checks for various flags and calls the respective functions. Here we have read the file character by character .

#include <stdio.h>
#include<string.h>
#include<stdio.h>

char * readFile(char *fileName);

int main(int argc, char **argv) {
extern char *optarg;
extern int optind;
int c, err = 0;
int cflag = 0, sflag = 0, fflag = 0;
char *substring;

// usage
static char usage[] = "usage: mywords [-cs] [-f substring] filename";

while ((c = getopt(argc, argv, "csf:")) != -1)
switch (c) {
case 'c':
cflag = 1;
break;

case 's':
sflag = 1;
break;

case 'f':
fflag = 1;
substring = optarg;
break;

case '?':
err = 1;
break;
}

if (fflag == 1) {
printf("%s substring ", substring);
}
char filename[25];
*filename=argv[optind]; //getting filename
  
char target_str[1000];
*target_str=readFile(filename);
  


if(sflag==1){
printSortedWords(target_str);
}
  
if(cflag==1){
countWords(target_str);
}
  
if(fflag==1){
findSubString(target_str,substring);
}
}

//function to read file
char * readFile(char *fileName)
{
FILE *file;
char *str = malloc(1000 * sizeof(char)); //assumed maximum size of file 1000 bytes
file = fopen(fileName, "r");
do
{
*str++ = (char)fgetc(file);

} while(*str != EOF);
return str;
}

//function to count number of words and print
void countWords(char *s){

int count=0;

for (int i = 0;s[i] != '\0';i++){

if (s[i] == ' ' || s[i]== ',' || s[i] ==';' || s[i]=='?' || s[i]=='\n' ) /* Checking for each punctuation */

{count++;
if(s[i+1]==' ')
i++;
  
}
}

printf("Count of Words: %d\n", count + 1);/* count +1 to count the last word*/

}


//function to find occurences of substring
void findSubString(char *target_str, char *sub_str){
int l1 = strlen(target_str);
int l2 = strlen(sub_str);
int count1=0;
//length of 2 strings
for (int i = 0; i < l1;)
{
int j = 0;
int k=i;
int count = 0;
while ((target_str[k] == sub_str[j]))//checking character by character
{
count++;
k++;
j++;
}
if (count == l2)//substring found
{
count1++;   
count = 0;
i++;
}
else
i++;//substring not found
}
printf("Number of occurences of %s in %s = %d", sub_str,target_str, count1);
}

//function to print sorted words
void printSortedWords (char *target_str)
{
int count = 0;
int j = 0;
char s[50][50]; //maximum 50 words of 50 characters each

for (int i = 0; target_str[i] != '\0'; i++)
{

if (target_str[i] == ' ' || target_str[i] == ',' || target_str[i] == ';'
|| target_str[i] == '?' || target_str[i] == '\n')
/* Checking for each punctuation and copying each word to different string */
{
count++;
j = 0;
if (s[i + 1] == ' ')
i++;
}
else
{
s[count][j] = target_str[i];
j++;
}

}

//sorting of Strings
char temp[50];
for (int i = 0; i <= count; i++)
for (j = i + 1; j <= count; j++)
{
if (strcmp (s[i], s[j]) > 0)
{
strcpy (temp, s[i]);
strcpy (s[i], s[j]);
strcpy (s[j], temp);
}
}
printf ("Sorted Words:");
for (int i = 0; i <= count; i++)
puts (s[i]);


}

Sample Input:

-cs -f "dsgdsh" hello.txt

Sample Output:


Related Solutions

Your assignment is to write a C++ program to read a text file containing the information...
Your assignment is to write a C++ program to read a text file containing the information of the employees of a company, load them into memory and perform some basic human resources operations. This assignment will help you practice: multiple file programming, classes, public and private methods, dynamic memory allocation, constructors and destructors, singly linked list and files. Implementation This lab assignment gives you the opportunity to practice creating classes and using dynamic memory in one of the required classes....
Design a program that will read each line of text from a file, print it out...
Design a program that will read each line of text from a file, print it out to the screen in forward and reverse order and determine if it is a palindrome, ignoring case, spaces, and punctuation. (A palindrome is a phrase that reads the same both forwards and backwards.) Example program run: A Toyota's a Toyota atoyoT a s'atoyoT A This is a palindrome! Hello World dlroW olleH This is NOT a palindrome! Note: You are only designing the program...
Write a C++ program to open and read a text file and count each unique token...
Write a C++ program to open and read a text file and count each unique token (word) by creating a new data type, struct, and by managing a vector of struct objects, passing the vector into and out of a function. Declare a struct TokenFreq that consists of two data members: (1) string value; and (2) int freq; Obviously, an object of this struct will be used to store a specific token and its frequency. For example, the following object...
C++ Write a whole program to read 50 salaries from the file “Salaries.txt” and print them...
C++ Write a whole program to read 50 salaries from the file “Salaries.txt” and print them on the screen (each value on a separate line), you have to also save the grades (each value on a separate line) into another file “SalariesWithBonus.txt” after you add a bonus of two percent to each salary (example For the salary 100000 a bonus of 2000 will be added as 100000 X 0.02 = 2000). Your code should check whether the file “Salaries.txt” opened...
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
(C++) Write a program to read from a grade database (data.txt). The database (text file) has...
(C++) Write a program to read from a grade database (data.txt). The database (text file) has students names, and grades for 10 quizzes.Use the given function prototypes to write the functions. Have main call your functions. The arrays should be declared in main() and passed to the functions as parameters. This is an exercise in parallel arrays, int and char 2 dim arrays. Function prototypes: int readData(ifstream &iFile, int scores[][10], char names[][30]); This functions takes the file stream parameter inFile...
C++ programming question Write a program that will read input from a text file called "theNumbers.txt"...
C++ programming question Write a program that will read input from a text file called "theNumbers.txt" (you will have to provide your own when debugging). The text file that is to be opened is formatted a certain way, namely, there is always one integer, one character (representing an operation), another integer, and then a new line character, with spaces between each item. A sample text file is provided below. theNumbers.txt 144 + 26 3 * 18 88 / 4 22...
You have to write a program that will read an array from a file and print...
You have to write a program that will read an array from a file and print if the numbers in the file are right truncatable primes. A right truncatable prime is a prime number, where if you truncate any numbers from the right, the resulting number is still prime. For example, 3797 is a truncatable prime number number because 3797, 379, 37, and 3 are all primes. Input-Output format: Your program will take the file name as input. The first...
You have to write a program that will read an array from a file and print...
You have to write a program that will read an array from a file and print if the numbers in the file are right truncatable primes. A right truncatable prime is a prime number, where if you truncate any numbers from the right, the resulting number is still prime. For example, 3797 is a truncatable prime number number because 3797, 379, 37, and 3 are all primes. Input-Output format: Your program will take the file name as input. The first...
Write a complete C program that read the text below and save the text in a...
Write a complete C program that read the text below and save the text in a new file "second.txt" with the same text written in all uppercase. "Beedle the Bard was an English wizard and author of wizarding fairytales. Beedle was born in Yorkshire, England. At some point in his life he wrote The Tales of Beedle the Bard . The only known image of Beedle is a woodcut that shows him with a "luxuriant" beard. Beedle wrote in ancient...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT