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

C programming String Search Develop a C program that searches a le for a given s

ID: 3761496 • Letter: C

Question

C programming

String Search
Develop a C program that searches a le for a given string. Your program should
• Ask the user to enter the le to be searched.
• Ask the user to enter the target string (string can be longer than one word, but no longer than a line)
• Locate the target string in the le. NOTE: the target string may also be contained within the string read from the le. Your program should be able to identify the target string as a part of another strings.
• Print the line number as well as the entire line where a match occurs.   •Write comments to your code.

I can use strings and arrays. Hope someone can help me.

Explanation / Answer

/**C program that prompts user to enter the name of the file and then the search string.
Then search the string in the file and prints the line number and line on which the string is found.
Otherwiser print an message*/

//search.c
//header files
#include<stdio.h>
#include<cstdlib>
#include<string.h>
#include<conio.h>

int main()
{

   //character array
   char fileName[40];
   char search[80];
   printf("Enter file name : ");
   //read fileName from user
   scanf("%s",fileName);

   printf("Enter search string : ");
   //read search string
   scanf("%s",search);

   //open file for reading
   FILE *fp=fopen(fileName,"r");


   //check if file fp exists
   if(!fp)
   {
       printf("File doesnot exist.!");
       exit(0);
   }

   const int size=512;
   int lineNum=1;
   int result=0;
   char line[size];

   printf("Search Results ");


   //read lines from the file
   while(fgets(line,512,fp)!=NULL && result==0)
   {

       //check for mathching strstr returns position of the searcing string in line
       //if it is not null
       if(strstr(line,search)!=NULL)
       {
           //print line number
           printf("Line number %d ",lineNum);
           //print line
           printf("Line : %s ",line);
           //set result to one
           result=1;
       }
       else
       {
           //otherwise increment the lineNum by one
           lineNum++;
       }
   }

   //check if result is zero , print a message
   if(result==0)
   {
       printf("No matches are found for %s ",search);
   }

   getch();
   return 0;
}

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

Sample input.txt file

Every communication session involves two hosts. each with its own IP
port numbers in use. you can quickly determine whether the transaction was valid or invalid.
IANA and some security vendors maintain a list ofwell-known port numbers ...

sample output:

Enter file name : input.txt
Enter search string : port
Search Results
Line number 2
Line : port numbers in use. you can quickly determine whether the transaction wa
s valid or invalid.