WRITE THE FUNCTION DEFINITION (assume all necessary #includes) 18. (1S poinsy) F
ID: 3731051 • Letter: W
Question
WRITE THE FUNCTION DEFINITION (assume all necessary #includes) 18. (1S poinsy) Finish writing the function definition for the int function filesearch( which takes in two parameters: a const char pointer (a string) filename that represents the name of a text file. o a const char pointer(a string) word that represents a word for which you are searching through the file. You can assume that the file contains more than one line of text. Each line in the file contains exactly one word (dess than 80 characters, with no whitespace), followed immediately Iby either a carriage return (CIn or an end of file marker (BOF The function should: open up the named file for reading if the 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 · if the function reaches the end-of file without finding a match, the function should close the file and return a -1 This fiunction itself performs no input from or output to the console! The only input is from the file By way of example. ithe file ax cotains (er 1 CarELage CotuEn this isccr> it then the call: 1ineNumber filesearch("x.txt") should set lineNumber to 2 (since "is" is on line 2), tdon't worty about "aagie aunbera ) int fileSearch(Explanation / Answer
// FileTestPro.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#pragma warning(disable:4996)
using namespace std;
int fileSearch(const char* fileName, char* word)
{
FILE* fp;
fopen_s(&fp, fileName, "r");
if (!fp)
{
printf("file pointer is NULL!");
return -2;
}
char line[80] = {0};
int lineNo = 1;
char strWord[20] = {0};
bool isWordFound = false;
while (fgets(line, 80, fp))
{
int i = 0, j = 0;
while (line[i] != ' ')
{
if (line[i] != ' ')
{
strWord[j++] = line[i];
}
if (0 == strcmp(strWord, word))
{
printf("word found::%s at line no. %d", word, lineNo);
for (int k = 0; k < 20; ++k) { strWord[k] = ''; }
j = 0;
i++;
isWordFound = true;
break;
}
i++;
}
lineNo++;
}
fclose(fp);
if (false == isWordFound)
{
return -1;
}
return 0;
}
int main()
{
char fileName[20] = "FileTest.txt";
char wordToSearchInFile[20] = "";
printf("Enter word to search in file::");
scanf("%s", wordToSearchInFile);
int retVal = fileSearch(fileName, wordToSearchInFile);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.