In: Computer Science
program c
Write a program called filesearch that accepts two command-line arguments:
If the user did not supply both arguments, the program should display an error message and exit.
The program opens the given filename. Each line that contains the given string is displayed. Use the strstr function to search each line for the string. You may assume no line is longer than 255 characters.
The matching lines are displayed to standard output (normally the screen).
Program
#include <stdio.h>
#include <string.h>
//main function
int main(int argc, char *argv[])
{
//check proper number of arguments
if(argc!=3){
printf("Error: number of arguments mismatch!\n");
return 1;
}
FILE *f;
char line[255], *t;
//open the file
f = fopen(argv[2], "r");
//check if file not exist
if(f==NULL){
printf("Error: file not exist!\n");
return 1;
}
//processing
while(fgets(line, 255, f)!=NULL)
{
//check if the line contains the given string
if ((t=strstr(line, argv[1]))!=NULL)
//display the line contains the given string
printf("%s\n", line);
}
return 0;
}
in.txt
Four score and seven years ago our fathers brought forth on this
continent, a new nation, conceived in Liberty, and dedicated to the
proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that
nation, or any nation so conceived and so dedicated, can long
endure.
Output:
./a.out civil in.txt
Now we are engaged in a great civil war, testing whether that
nation, or any nation so conceived and so dedicated, can long
endure.
Solving your question and
helping you to well understand it is my focus. So if you face any
difficulties regarding this please let me know through the
comments. I will try my best to assist you.
Thank you.