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

includes) WRITE THE FUNCTION DEFINITION (me all necessary 3 char pointer fa seri

ID: 3731031 • Letter: I

Question

includes) WRITE THE FUNCTION DEFINITION (me all necessary 3 char pointer fa serine ellename that represents the name of a text file throsgeh he erine) word that represents a word for which you are hich enish wviting the Runction deuition for the int function esso . a const char pointer immediately assume that the ile followed contains more than one line of text. Each line in the ile by The flanction should either a carriage return An' or an end of file marker (EOF - open up the named file for reading irthe file cannot be opened, the function should return a-2 otherwise, the function should read the lines of the file into a buffer, one word/line at a time, keeping track of line numbers (start counting at 1). if a string read - in is an exact match to the word passed in, the function should close the file and return the current line number ifthe function reaches the end or me without finding a match, the function should close the file and returm a -1 · This fonction itselfperforms no input from or ouiput to the console! The only input is from the file Ey thisscrs issCr> then the call: should set lineNumber to 2 (since "is" is on line 2). (don't worry about "magio numbers int fileSearch( 1ineNumberfilesearch ("x.txt", "is")

Explanation / Answer

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

int fileSearch(char filename[], char word[])
{
char line[1000];
FILE *fptr;
int line_number = 0;
if ((fptr = fopen("sample.txt", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
return -2;   
}

// reads text until newline
while (fgets(line, sizeof(line), fptr)) {
line_number++;
if(strstr(line,word)){
fclose ( fptr );
return line_number;
break;
}
}

return -1;
  
}

int main(int argc, char const *argv[])
{
printf("Line number for the selected word is: %d ", fileSearch("sample.txt","hasa"));
return 0;
  
}

INPUT FILe

testing file
here is the word
over and out
yes sir
now go back
hasa masa chada
hila nila ptali
patnito sdcard bim
hal mali
stop this now.

OUTPUT:

dps@machine:~/Desktop$ gcc read_file.c
dps@machine:~/Desktop$ ./read_file
Line number for the selected word is: 6