Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a complete C program that will parse an input file and search for occurren

ID: 3884364 • Letter: W

Question

Write a complete C program that will parse an input file and search for occurrences of a word pattern. The program will output the total number of occurrences and all of the lines with the word pattern in it.

1. Command-Line Arguments:

Read in the command-line arguments and verify that there are three parameters: the program name, an input file that is the name of the file you will be working with, and the word pattern that you are searching for. If the number of parameters is incorrect, print out a usage message and terminate the program.

2. File I/O:

Open the file that was given as a command-line argument to your program. Then, read through the file and print the following information: the total number of lines in the file, the number of characters in the longest line of the file, and the longest line of the file.

3. Pattern Matching (i.e., grep):

Create a data structure that holds all of the information for each occurrence of a word pattern. For example, it should hold the line number and the contents of the line it occurs on. Print all of the information (i.e., the line number and the contents of the line it occurs on), including the total number occurrences of the word pattern.

Explanation / Answer

[1]

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

int main(int argc, char *argv[]) {
int count, errno;

// To Verify Number of parameter in Command line
if(argc < 3 || argc > 3) {
  display(argv[0]);
  exit(1);
}

  // Pass Filename and String to find count
count = find(argv[1], argv[2]);
if(count == -1) {
  perror("Error");
  printf("Error number = %d ", errno);
  exit(1);
}
return(0);
}

void display(char *filename) {
printf("Display: %s <file> <string> ", filename);
}


int find(char *fname, char *str) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[512];
fp = fopen(f,fname, "r");

while(fgets(temp, 512, fp) != NULL) {
  if((strstr(temp, str)) != NULL) {
   printf("line: %d ", line_num);
   printf(" %s ", temp);
   find_result++;
  }
  line_num++;
}

if(find_result == 0) {
  printf(" Couldn't find a match. ");
}

//Close the file if still open.
if(fp) {
  fclose(fp);
}
   return(0);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote