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

Scanning Text Files Develop a C program that searches a text file for a given st

ID: 3680487 • Letter: S

Question

Scanning Text Files Develop a C program that searches a text file for a given string. Your program should

• Ask the user for a string to search for.

o The target string can be more than one word

• Print the line number and the string where the target string was detected.

Enter the target string:habit of using

7. hear me using the same words in my defense which I have been in the habit of using, and which most of you may have heard in the agora, and at the tables of the money-changers, or anywhere else, I would ask you not to be surprised

Enter the target string:men of

1. How you have felt, O men of Athens, at hearing the speeches of my accusers, I cannot tell; but I know that their persuasive words almost made me forget who I was - such was the effect of them; and yet they have hardly spoken a word

6. right, and that at my time of life I ought not to be appearing before you, O men of Athens, in the character of a juvenile orator - let no one expect this of me. And I must beg of you to grant me one favor, which is this - If you

Full text file:

How you have felt, O men of Athens, at hearing the speeches of my accusers, I cannot tell; but I know that their persuasive words almost made me forget who I was - such was the effect of them; and yet they have hardly spoken a word

Explanation / Answer

#include <stdio.h>
int FindStr(FILE *f, char *str);
int main()
{
char *str;
FILE *f;
int pos;
f = fopen("duom.txt", "r");
printf("Write a string to searc for: ");
scanf("%s", str);
pos = FindStr(f, str);
if (pos != -1)
printf("String is found, it's position is: %d ", pos);
else
printf("String is not found! ");
fclose(f);
getchar();
return(0);
}

int FindStr(FILE *f, char *str)
{
int s_pos; //string position in the text
int c_pos; //char position in the text
char *string;
char ccnt; //char count

s_pos = -1;
c_pos = 0;
string = malloc(strlen(str));
while (!feof(f))
{
if (c_pos == 0)
for (ccnt = 1; ccnt <= strlen(str); ccnt++)
if (!feof(f))
string[ccnt - 1] = getc(f);
if (c_pos != 0)
if (!feof(f))
{
for (ccnt = 0; ccnt <= strlen(str) - 2; ccnt++)
string[ccnt] = string[ccnt + 1];
string[strlen(str) - 1] = getc(f);
}   
if (strcmp(string, str) == 0)
{
s_pos = c_pos;
break;
}
c_pos++;
}
return(s_pos);
}

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